Sunteți pe pagina 1din 105

JAVA Interview Questions

Glossary of Terms, Core Java, JDBC and Java 1.5 features

========================== ***************** =========================

Glossary of Terms
A
abstract
A Java(TM) programming language keyword used in a class definition to specify that a
class is not to be instantiated, but rather inherited by other classes. An abstract class can
have abstract methods that are not implemented in the abstract class, but in subclasses.
abstract class
A class that contains one or more abstract methods, and therefore can never be
instantiated. Abstract classes are defined so that other classes can extend them and make
them concrete by implementing the abstract methods.
abstract method
A method that has no implementation.
actual parameter list
The arguments specified in a particular method call. See also formal parameter list.
API
Application Programming Interface. The specification of how a programmer writing an
application accesses the behavior and state of classes and objects.
applet
A program written in the Java(TM) programming language to run within a web browser
compatible with the Java platform, such as HotJava(TM) or Netscape Navigator(TM).
argument
A data item specified in a method call. An argument can be a literal value, a variable, or
an expression.
array
A collection of data items, all of the same type, in which each item's position is uniquely
designated by an integer.
ASCII
American Standard Code for Information Interchange. A standard assignment of 7-bit
numeric codes to characters. See also Unicode.
atomic
Refers to an operation that is never interrupted or left in an incomplete state under any
circumstance.

B
Bean
A reusable software component. Beans can be combined to create an application.
binary operator
An operator that has two arguments.
bit
The smallest unit of information in a computer, with a value of either 0 or 1.
bitwise operator

y.rajashekher@gmail.com Page 1
An operator that manipulates two values comparing each bit of one value to the
corresponding bit of the other value.
block
In the Java(TM) programming language, any code between matching braces. Example: {
x = 1; }.
boolean
Refers to an expression or variable that can have only a true or false value. The Java(TM)
programming language provides the boolean type and the literal values true and false.
.
break
A Java(TM) programming language keyword used to resume program execution at the
statement immediately following the current statement. If followed by a label, the
program resumes execution at the labeled statement.
byte
A sequence of eight bits. The Java(TM) programming language provides a corresponding
byte type.
bytecode
Machine-independent code generated by the Java(TM) compiler and executed by the Java
interpreter.

C
case
A Java(TM) programming language keyword that defines a group of statements to begin
executing if a value specified matches the value defined by a preceding "switch"
keyword.
casting
Explicit conversion from one data type to another.
catch
A Java(TM) programming language keyword used to declare a block of statements to be
executed in the event that a Java exception, or run time error, occurs in a preceding "try"
block.
char
A Java(TM) programming language keyword used to declare a variable of type character.
class
In the Java(TM) programming language, a type that defines the implementation of a
particular kind of object. A class definition defines instance and class variables and
methods, as well as specifying the interfaces the class implements and the immediate
superclass of the class. If the superclass is not explicitly specified, the superclass will
implicitly be Object.
class method
A method that is invoked without reference to a particular object. Class methods affect
the class as a whole, not a particular instance of the class. Also called a static method. See
also instance method.
classpath
A classpath is an environmental variable which tells the Java(TM) virtual machine* and
Java technology-based applications (for example, the tools located in the JDK(TM)

y.rajashekher@gmail.com Page 2
1.1.X\bin directory) where to find the class libraries, including user-defined class
libraries.
class variable
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. See
also instance variable.
client
In the client/server model of communcations, the client is a process that remotely
accesses resources of a compute server, such as compute power and large memory
capacity.
comment
In a program, explanatory text that is ignored by the compiler. In programs written in the
Java(TM) programming language, comments are delimited using // or /*...*/.
compilation unit
The smallest unit of source code that can be compiled. In the current implementation of
the Java(TM) platform, the compilation unit is a file.
compiler
A program to translate source code into code to be executed by a computer. The
Java(TM) compiler translates source code written in the Java programming language into
bytecode for the Java virtual machine*. See also interpreter.
compositing
The process of superimposing one image on another to create a single image.
constructor
A pseudo-method that creates an object. In the Java(TM) programming language,
constructors are instance methods with the same name as their class. Constructors are
invoked using the new keyword.
const
This is a reserved Java(TM) programming language keyword. However, it is not used by
current versions of the Java programming language.
continue
A Java(TM) programming language keyword used to resume program execution at the
end of the current loop. If followed by a label, "continue" resumes execution where the
label occurs.
core class
A public class (or interface) that is a standard member of the Java(TM) Platform. The
intent is that the core classes for the Java platform, at minimum, are available on all
operating systems where the Java platform runs. A program written entirely in the Java
programming language relies only on core classes, meaning it can run anywhere. See
also, 100% Pure Java(TM).
Core Packages
The required set of APIs in a Java platform edition which must be supported in any and
all compatible implementations.
.

D
declaration

y.rajashekher@gmail.com Page 3
A statement that establishes an identifier and associates attributes with it, without
necessarily reserving its storage (for data) or providing the implementation (for methods).
See also definition.
default
A Java(TM) programming language keyword optionally used after all "case" conditions
in a "switch" statement. If all "case" conditions are not matched by the value of the
"switch" variable, the "default" keyword will be executed.
definition
A declaration that reserves storage (for data) or provides implementation (for methods).
See also declaration.
deprecation
Refers to a class, interface, constructor, method or field that is no longer recommended,
and may cease to exist in a future version.
derived from
Class X is "derived from" class Y if class X extends class Y. See also subclass,
superclass.
distributed
Running in more than one address space.
do
A Java(TM) programming language keyword used to declare a loop that will iterate a
block of statements. The loop`s exit condition can be specified with the "while" keyword.
double
A Java(TM) programming language keyword used to define a variable of type double.
double precision
In the Java(TM) programming language specification, describes a floating point number
that holds 64 bits of data. See also single precision.

E
else
A Java(TM) programming language keyword used to execute a block of statements in the
case that the test condition with the "if" keyword evaluates to false.
EmbeddedJava(TM) Technology
The availability of Sun's Java 2 Platform, Micro Edition technology under a restrictive
license agreement that allows a licensee to leverage certain Java technologies to create
and deploy a closed-box application that exposes no APIs.
encapsulation
The localization of knowledge within a module. Because objects encapsulate data and
implementation, the user of an object can view the object as a black box that provides
services. Instance variables and methods can be added, deleted, or changed, but as long as
the services provided by the object remain the same, code that uses the object can
continue to use it without being rewritten. See also instance variable, instance method.
exception
An event during program execution that prevents the program from continuing normally;
generally, an error. The Java(TM) programming language supports exceptions with the
try, catch, and throw keywords. See also exception handler.
exception handler

y.rajashekher@gmail.com Page 4
A block of code that reacts to a specific type of exception. If the exception is for an error
that the program can recover from, the program can resume executing after the exception
handler has executed.
executable content
An application that runs from within an HTML file. See also applet.
extends
Class X extends class Y to add functionality, either by adding fields or methods to class
Y, or by overriding methods of class Y. An interface extends another interface by adding
methods. Class X is said to be a subclass of class Y. See also derived from.

F
field
A data member of a class. Unless specified otherwise, a field is not static.
final
A Java(TM) programming language keyword. You define an entity once and cannot
change it or derive from it later. More specifically: a final class cannot be subclassed, a
final method cannot be overridden and a final variable cannot change from its initialized
value.
finally
A Java(TM) programming language keyword that executes a block of statements
regardless of whether a Java Exception, or run time error, occurred in a block defined
previously by the "try" keyword.
float
A Java(TM) programming language keyword used to define a floating point number
variable.
for
A Java(TM) programming language keyword used to declare a loop that reiterates
statements. The programmer can specify the statements to be executed, exit conditions,
and initialization variables for the loop.
FTP
The basic Internet File Transfer Protocol. FTP, which is based on TCP/IP, enables the
fetching and storing of files between hosts on the Internet. See also TCP/IP.
formal parameter list
The parameters specified in the definition of a particular method. See also actual
parameter list.

G
garbage collection
The automatic detection and freeing of memory that is no longer in use. The Java(TM)
runtime system performs garbage collection so that programmers never explicitly free
objects.
goto
This is a reserved Java(TM) programming language keyword. However, it is not used by
current versions of the Java programming language.

H
hexadecimal
y.rajashekher@gmail.com Page 5
The numbering system that uses 16 as its base. The marks 0-9 and a-f (or equivalently A-
F) represent the digits 0 through 15. In programs written in the Java(TM) programming
language, hexadecimal numbers must be preceded with 0x. See also octal.
hierarchy
A classification of relationships in which each item except the top one (known as the
root) is a specialized form of the item above it. Each item can have one or more items
below it in the hierarchy. In the Java(TM) class hierarchy, the root is the Object class.
HotJava(TM) Browser
An easily customizable Web browser developed by Sun Microsystems, which is written
in the Java(TM) programming language.
HTML
HyperText Markup Language. This is a file format, based on SGML, for hypertext
documents on the Internet. It is very simple and allows for the embedding of images,
sounds, video streams, form fields and simple text formatting. References to other objects
are embedded using URLs.
HTTP
HyperText Transfer Protocol. The Internet protocol, based on TCP/IP, used to fetch
hypertext objects from remote hosts. See also TCP/IP.

I
IDL
Interface Definition Language. APIs written in the Java(TM) programming language that
provide standards-based interoperability and connectivity with CORBA (Common Object
Request Broker Architecture).
identifier
The name of an item in a program written in the Java(TM) programming language.
if
A Java(TM) programming language keyword used to conduct a conditional test and
execute a block of statements if the test evaluates to true.
implements
A Java(TM) programming language keyword optionally included in the class declaration
to specify any interfaces that are implemented by the current class.
import
A Java(TM) programming language keyword used at the beginning of a source file that
can specify classes or entire packages to be referred to later without including their
package names in the reference.
inheritance
The concept of classes automatically containing the variables and methods defined in
their supertypes. See also superclass, subclass.
instance
An object of a particular class. In programs written in the Java(TM) programming
language, an instance of a class is created using the new operator followed by the class
name.
instance method
Any method that is invoked with respect to an instance of a class. Also called simply a
method. See also class method.

y.rajashekher@gmail.com Page 6
instance variable
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. See also
class variable.
instanceof
A two-argument Java(TM) programming language keyword that tests whether the run-
time type of its first argument is assignment compatible with its second argument.
int
A Java(TM) programming language keyword used to define a variable of type integer.
interface
A Java(TM) programming language keyword used to define a collection of method
definitions and constant values. It can later be implemented by classes that define this
interface with the "implements" keyword.
Internet
An enormous network consisting of literally millions of hosts from many organizations
and countries around the world. It is physically put together from many smaller networks
and data travels by a common set of protocols.
IP
Internet Protocol. The basic protocol of the Internet. It enables the unreliable delivery of
individual packets from one host to another. It makes no guarantees about whether or not
the packet will be delivered, how long it will take, or if multiple packets will arrive in the
order they were sent. Protocols built on top of this add the notions of connection and
reliability. See also TCP/IP.
interpreter
A module that alternately decodes and executes every statement in some body of code.
The Java(TM) interpreter decodes and executes bytecode for the Java virtual machine*.
See also compiler, runtime system.

J
JAE
Java(TM) Application Environment. The source code release of the Java Development
Kit (JDK(TM)) software.
JAR Files (.jar)
Java ARchive. A file format used for aggregating many files into one.
JAR file format
JAR (Java Archive) is a platform-independent file format that aggregates many files into
one. Multiple applets written in the Java(TM) programming language, and their requisite
components (.class files, images, sounds and other resource files) can be bundled in a
JAR file and subsequently downloaded to a browser in a single HTTP transaction. It also
supports file compression and digital signatures.
Java(TM)
Sun's trademark for a set of technologies for creating and safely running software
programs in both stand-alone and networked environments.
Java Application Environment (JAE)
The source code release of the Java Development Kit (JDK(TM)) software.
JavaBeans(TM)
A portable, platform-independent reusable component model.
y.rajashekher@gmail.com Page 7
Java Blend(TM)
A product that enables developers to simplify database application development by
mapping database records to objects in the Java(TM) programming language (Java
objects) and Java objects to databases.
Java Card(TM) API
An ISO 7816-4 compliant application environment focused on smart cards.
JavaCheck(TM)
A tool for checking compliance of applications and applets to a specification.
JavaChip(TM)
Sun's processor, which executes bytecode for the Java(TM) virtual machine* natively.
With a JavaChip processor, bytecode bypasses the virtual machine or just-in-time
compiler stage to go directly to the processor.
Java(TM) Compatibility Kit (JCK)
A test suite, a set of tools, and other requirements used to certify a Java platform
implementation conformant both to the applicable Java platform specifications and to
Java Software reference implementations.
Java Database Connectivity (JDBC(TM))
An industry standard for database-independent connectivity between the Java(TM)
platform and a wide range of databases. The JDBC(TM) provides a call-level API for
SQL-based database access.
Java Developer Connection(SM)
A service designed for individual developers, providing online training, product
discounts, feature articles, bug information, and early access capabilities.
Java Development Kit (JDK(TM))
A software development environment for writing applets and applications in the Java
programming language.
Java(TM) Electronic Commerce Framework
A structured architecture for the development of electronic commerce applications in the
Java(TM) programming language.
Java(TM) Enterprise API
This API makes it easy to create large-scale commercial and database applications that
can share multimedia data with other applications within an organization or across the
Internet. Four APIs have been designed within the Java(TM) Enterprise API family.
Java(TM) Foundation Classes (JFC)
An extension that adds graphical user interface class libraries to the Abstract Windowing
Toolkit (AWT).
Java(TM) Interface Definition Language (IDL)
APIs written in the Java programming language that provide standards-based
interoperability and connectivity with CORBA (Common Object Request Broker
Architecture).
Java(TM) Media APIs
A set of APIs that support the integration of audio and video clips, 2D fonts, graphics,
and images as well as 3D models and telephony.
Java(TM) Media Framework

y.rajashekher@gmail.com Page 8
The core framework supports clocks for synchronizing between different media (e.g.,
audio and video output). The standard extension framework allows users to do full audio
and video streaming.
Java Naming and Directory Interface(TM) (JNDI)
A set of APIs that assists with the interfacing to multiple naming and directory services.
JavaOS(TM)
An Java(TM) technology-based operating system that is optimized to run on a variety of
computing and consumer platforms. The JavaOS(TM) operating environment provides a
runtime specifically tuned to run applications written in the Java programming language
directly on hardware platforms without requiring a host operating system.
JavaPlan(TM)
An object-oriented design and diagramming tool written in the Java(TM) programming
language.
Java(TM) Platform
Consists of a language for writing programs ("the Java(TM) programming language"); a
set of APIs, class libraries, and other programs used in developing, compiling, and error-
checking programs; and a virtual machine which loads and executes the class files.

In addition, the Java platform is subject to a set of compatibility requirements to ensure


consistent and compatible implementations. Implementations that meet the compatibility
requirements may qualify for Sun's targeted compatibility brands.

The Java(TM) 2 platform is the current generation of the Java platform.


Java(TM) Platform Editions
A Java platform "edition" is a definitive and agreed-upon version of the Java platform
that provides the functionality needed over a broad market segment.

An edition is comprised of two kinds of API sets: (i) "core packages," which are essential
to all implementations of a given platform edition, and (ii) "optional packages," which are
available for a given platform edition and which may be supported in a compatible
implementation.

There are 3 distinct editions of the Java Platform:

* Java 2 Platform, Enterprise Edition:


The edition of the Java platform that is targeted at enterprises to enable development,
deployment, and management of multi-tier server-centric applications.

* Java 2 Platform, Standard Edition:


The edition of the Java platform that enables development, deployment, and management
of cross-platform, general-purpose applications.

* Java 2 Platform, Micro Edition:


The edition of the Java platform that is targeted at small, standalone or connectable
consumer and embedded devices to enable development, deployment, and management

y.rajashekher@gmail.com Page 9
of applications that can scale from smart cards through mobile devices and set-top boxes
to conventional computing devices.
Java(TM) Remote Method Invocation (RMI)
A distributed object model for Java(TM) program to Java program, in which the methods
of remote objects written in the Java programming language can be invoked from other
Java virtual machines*, possibly on different hosts.
Java(TM) Runtime Environment (JRE)
A subset of the Java Development Kit (JDK(TM)) for end-users and developers who
want to redistribute the runtime environment alone. The Java runtime environment
consists of the Java virtual machine*, the Java core classes, and supporting files.
JavaSafe(TM)
A tool for tracking and managing source file changes, written in the Java(TM)
programming language.
JavaScript(TM)
A Web scripting language that is used in both browsers and Web servers. Like all
scripting languages, it is used primarily to tie other components together or to accept user
input.
Java Studio(TM)
The first program that allows you to easily create Java(TM) technology-based
applications and applets without having to know the Java programming language.
Java(TM) Technologies
A set of technologies that enable the creation and safe running of software programs in
both stand-alone and networked environments.
Java(TM) virtual machine (JVM)*
Sun's specification for or implementation of a software "execution engine" that safely and
compatibly executes the byte codes in Java class files on a microprocessor (whether in a
computer or in another electronic device).

* Java HotSpot(TM) performance engine - Sun's ultra-high-performance engine for


implementing the Java runtime environment which features an adaptive compiler that
dynamically optimizes the performance of running applications.

* KJava(TM) virtual machine - Sun's small-footprint, highly optimized foundation of a


runtime environment within the Java 2 Platform, Micro Edition. Derived from the Java
virtual machine, it is targeted at small connected devices and can scale from 30KB to
approximately 128KB, depending on the target device's functionality.

* Java Card(TM) virtual machine - Sun's ultra-small-footprint, highly-optimized


foundation of a runtime environment within the Java 2 Platform, Micro Edition. Derived
from the Java virtual machine, it is targeted at smart cards and other severely memory-
constrained devices and can run in devices with memory as small as 24K of ROM, 16K
of EEPROM, and 512 bytes of RAM.
Java Web Server(TM)
The easy-to-use, extensible, easy-to-administer, secure, platform-independent solution to
speed and simplify the deployment and management of your Internet and Intranet Web

y.rajashekher@gmail.com Page 10
sites. It provides immediate productivity for robust, full-featured, Java technology-based
server applications.
Java Workshop(TM)
A complete set of tools integrated into a single environment for managing programming
with Java technology. The Java Workshop software uses a highly modular structure that
enables you to easily plug new tools into the overall structure.
Java(TM) wallet
A user interface, built on the Java(TM) Electronic Commerce Framework, which allows
for online purchases, value transfers, and administrative functions.
JavaSpaces(TM)
A technology that provides distributed persistence and data exchange mechanisms for
code in the Java(TM) programming language.
JavaSoft(TM)
A former business unit of Sun Microsystems, Inc., currently known as Sun Microsystems,
Inc., Java Software division.
JDBC(TM)
Java(TM) Database Connectivity. An industry standard for database-independent
connectivity between the Java platform and a wide range of databases. The JDBC
interface provides a call-level API for SQL-based database access.
JDK(TM)
Java(TM) Development Kit software. A software development environment for writing
applets and application in the Java programming language.
JFC
Java(TM) Foundation Class. An extension that adds graphical user interface class
libraries to the Abstract Windowing Toolkit (AWT).
Jini(TM) Technology
Sun's Jini technology includes a set of APIs that may be incorporated an optional package
for any Java 2 platform edition. This set of APIs enables transparent networking of
devices and services and eliminates the need for system or network administration
intervention by a user.

The Jini technology is currently an optional package available on all Java 2 platform
editions.
JMAPI
Java(TM) Management API. A collection of Java programming language classes and
interfaces that allow developers to build system, network, and service management
applications.
JNDI
Java Naming and Directory Interface(TM). A set of APIs that assist with the interfacing
to multiple naming and directory services.
JPEG
Joint Photographic Experts Group. An image file compression standard established by
this group. It achieves tremendous compression at the cost of introducing distortions into
the image which are almost always imperceptible.
JRE

y.rajashekher@gmail.com Page 11
Java(TM) runtime environment. A subset of the Java Developer Kit for end-users and
developers who want to redistribute the runtime environment. The Java runtime
environment consists of the Java virtual machine*, the Java core classes, and supporting
files.
Just-in-time (JIT) Compiler
A compiler that converts all of the bytecode into native machine code just as a Java(TM)
program is run. This results in run-time speed improvements over code that is interpreted
by a Java virtual machine*.
JVM
Java(TM) Virtual Machine*. The part of the Java Runtime Environment responsible for
interpreting bytecodes.

K
keyword
The Java(TM) programming language sets aside words as keywords - these words are
reserved by the language itself and therefore are not available as names for variables or
methods.

L
linker
A module that builds an executable, complete program from component machine code
modules. The Java(TM) linker creates a runnable program from compiled classes. See
also compiler, interpreter, runtime system.
literal
The basic representation of any integer, floating point, or character value. For example,
3.0 is a double-precision floating point literal, and "a" is a character literal.
local variable
A data item known within a block, but inaccessible to code outside the block. For
example, any variable defined within a method is a local variable and can't be used
outside the method.
long
A Java(TM) programming language keyword used to define a variable of type long.

M
member
A field or method of a class. Unless specified otherwise, a member is not static.
method
A function defined in a class. See also instance method, class method. Unless specified
otherwise, a method is not static.
Mosaic
A program that provides a simple GUI that enables easy access to the data stored on the
Internet. These data may be simple files or hypertext documents. Mosaic was written by a
team at NCSA.
multithreaded
Describes a program that is designed to have parts of its code execute concurrently. See
also thread.

y.rajashekher@gmail.com Page 12
N
native
A Java(TM) programming language keyword that is used in method declarations to
specify that the method is not implemented in the same Java source file, but rather in
another language
new
A Java(TM) programming language keyword used to create an instance of a class.
null
A Java(TM) programming language keyword used to specify an undefined value for
reference variables.

O
object
The principal building blocks of object-oriented programs. Each object is a programming
unit consisting of data (instance variables) and functionality (instance methods). See also
class.
object-oriented design
A software design method that models the characteristics of abstract or real objects using
classes and objects.
octal
The numbering system using 8 as its base, using the numerals 0-7 as its digits. In
programs written in the Java(TM) programming language, octal numbers must be
preceded with 0. See also hexadecimal.
Optional Packages
The set or sets of APIs in a Java platform edition which are available with and may be
supported in a compatible implementation.

Over time, optional packages may become required in an edition as the marketplace
requires them.
overloading
Using one identifier to refer to multiple items in the same scope. In the Java(TM)
programming language, you can overload methods but not variables or operators.
overriding
Providing a different implementation of a method in a subclass of the class that originally
defined the method.

P
package
A group of types. Packages are declared with the package keyword.
peer
In networking, any functional unit in the same layer as another entity.
PersonalJava(TM)
A Java runtime environment for network-connectable applications on personal consumer
devices for home, office, and mobile use.
pixel
The smallest addressable picture element on a display screen or printed page.
y.rajashekher@gmail.com Page 13
POSIX
Portable Operating System for UNIX(TM). A standard that defines the language interface
between the UNIX operating system and application programs through a minimal set of
supported functions.
private
A Java(TM) programming language keyword used in a method or variable declaration. It
signifies that the method or variable can only be accessed by other elements of its class.
process
A virtual address space containing one or more threads.
property
Characteristics of an object that users can set, such as the color of a window.
Profiles
A Profile is a collection of Java APIs that complements one or more Java 2 Platform
Editions by adding domain-specific capabilities. Profiles may also include other defined
Profiles. A profile implementation requires a Java 2 Platform Edition to create a complete
development and deployment environment in a targeted vertical market. Each profile is
subject to an associated set of compatibility requirements.

Profiles may be usable on one or more editions.

Some examples of profiles within the Java 2 Platform, Micro Edition are:

* PersonalJava(TM) - for non-PC products that need to display web-compatible Java-


based content

* Java Card(TM) - for secure smart cards and other severely memory-constrained
devices.
protected
A Java(TM) programming language keyword used in a method or variable declaration. It
signifies that the method or variable can only be accessed by elements residing in its
class, subclasses, or classes in the same package.
public
A Java(TM) programming language keyword used in a method or variable declaration. It
signifies that the method or variable can be accessed by elements residing in other
classes.

Q
R
reference
A data element whose value is an address.
return
A Java(TM) programming language keyword used to finish the execution of a method. It
can be followed by a value required by the method definition.
.
RMI
See Java Remote Method Invocation.
y.rajashekher@gmail.com Page 14
root
In a hierarchy of items, the one item from which all other items are descended. The root
item has nothing above it in the hierarchy. See also hierarchy, class, package.
RPC
Remote Procedure Call. Executing what looks like a normal procedure call (or method
invocation) by sending network packets to some remote host.
runtime system
The software environment in which programs compiled for the Java(TM) virtual
machine* can run. The runtime system includes all the code necessary to load programs
written in the Java programming language, dynamically link native methods, manage
memory, handle exceptions, and an implementation of the Java virtual machine, which
may be a Java interpreter.

S
Sandbox
Comprises a number of cooperating system components, ranging from security managers
that execute as part of the application, to security measures designed into the Java(TM)
virtual machine* and the language itself. The sandbox ensures that an untrusted, and
possibly malicious, application cannot gain access to system resources.
scope
A characteristic of an identifier that determines where the identifier can be used. Most
identifiers in the Java(TM) programming environment have either class or local scope.
Instance and class variables and methods have class scope; they can be used outside the
class and its subclasses only by prefixing them with an instance of the class or (for class
variables and methods) with the class name. All other variables are declared within
methods and have local scope; they can be used only within the enclosing block.
Secure Socket Layer (SSL)
A protocol that allows communication between a Web browser and a server to be
encrypted for privacy.
servlet
A server-side program that gives Java(TM) technology-enabled servers additional
functionality.
short
A Java(TM) programming language keyword used to define a variable of type short.
single precision
In the Java(TM) language specification, describes a floating point number with 32 bits of
data. See also double precision.
.
static
A Java(TM) programming language keyword used to define a variable as a class variable.
Classes maintain one copy of class variables regardless of how many instances exist of
that class. "static" can also be used to define a method as a class method. Class methods
are invoked by the class instead of a specific instance, and can only operate on class
variables.
static field
Another name for class variable.
static method
y.rajashekher@gmail.com Page 15
Another name for class method.
subarray
An array that is inside another array.
subclass
A class that is derived from a particular class, perhaps with one or more classes in
between. See also superclass, supertype.
subtype
If type X extends or implements type Y, then X is a subtype of Y. See also supertype.
superclass
A class from which a particular class is derived, perhaps with one or more classes in
between. See also subclass, subtype.
super
A Java(TM) programming language keyword used to access members of a class inherited
by the class in which it appears.
supertype
The supertypes of a type are all the interfaces and classes that are extended or
implemented by that type. See also subtype, superclass.
switch
A Java(TM) programming language keyword used to evaluate a variable that can later be
matched with a value specified by the "case" keyword in order to execute a group of
statements.
Swing Set
The code name for a collection of graphical user interface (GUI) components that runs
uniformly on any native platform which supports the Java(TM) virtual machine*.
Because they are written entirely in the Java programming language, these components
may provide functionality above and beyond that provided by native-platform
equivalents. (Contrast with AWT.)
synchronized
A keyword in the Java programming language that, when applied to a method or code
block, guarantees that at most one thread at a time executes that code.

T
TCP/IP
Transmission Control Protocol based on IP. This is an Internet protocol that provides for
the reliable delivery of streams of data from one host to another. See also IP.
Thin Client
A system that runs a very light operating system with no local system administration and
executes applications delivered over the network.
this
A Java(TM) programming language keyword that can be used to represent an instance of
the class in which it appears. "this" can be used to access class variables and methods.
thread
The basic unit of program execution. A process can have several threads running
concurrently, each performing a different job, such as waiting for events or performing a
time-consuming job that the program doesn't need to complete before going on. When a
thread has finished its job, the thread is suspended or destroyed. See also process.
throw
y.rajashekher@gmail.com Page 16
A Java(TM) programming language keyword that allows the user to throw an exception
or any class that implements the "throwable" interface.
throws
A Java(TM) programming language keyword used in method declarations that specify
which exceptions are not handled within the method but rather passed to the next higher
level of the program.
transient
A keyword in the Java programming language that indicates that a field is not part of the
serialized form of an object. When an object is serialized, the values of its transient fields
are not included in the serial representation, while the values of its non-transient fields
are included.
try
A Java(TM) programming language keyword that defines a block of statements that may
throw a Java language exception. If an exception is thrown, an optional "catch" block can
handle specific exceptions thrown within the "try" block. Also, an optional "finally"
block will be executed regardless of whether an exception is thrown or not.
type
A class or interface.

U
Unicode
A 16-bit character set defined by ISO 10646. See also ASCII. All source code in the
Java(TM) programming environment is written in Unicode.
URL
Uniform Resource Locator. A standard for writing a text reference to an arbitrary piece of
data in the WWW. A URL looks like "protocol://host/localinfo" where protocol specifies
a protocol to use to fetch the object (like HTTP or FTP), host specifies the Internet name
of the host on which to find it, and localinfo is a string (often a file name) passed to the
protocol handler on the remote host.
variable
An item of data named by an identifier. Each variable has a type, such as int or Object,
and a scope. See also class variable, instance variable, local variable.
virtual machine
An abstract specification for a computing device that can be implemented in different
ways, in software or hardware. You compile to the instruction set of a virtual machine
much like you'd compile to the instruction set of a microprocessor. The Java(TM) virtual
machine* consists of a bytecode instruction set, a set of registers, a stack, a garbage-
collected heap, and an area for storing methods.
void
A Java(TM) programming language keyword used in method declarations to specify that
the method does not return any value. "void" can also be used as a nonfunctional
statement.
volatile
A Java(TM) programming language keyword used in variable declarations that specifies
that the variable is modified asynchronously by concurrently running threads.
wait

y.rajashekher@gmail.com Page 17
A UNIX command which will wait for all background processes to complete, and
report their termination status.
while
A Java(TM) programming language keyword used to declare a loop that iterates a block
of statements. The loop`s exit condition is specified as part of the while statement.
world readable files
Files on a file system that can be viewed (read) by any user. For example: files residing
on web servers can only be viewed by Internet users if their permissions have been set to
world readable.
wrapper
An object that encapsulates and delegates to another object to alter its interface or
behavior in some way.

========================== ***************** =========================


Java Interview Questions
What if the main method is declared as private?

The program compiles properly but at runtime it will give Main method not public. message.

What is meant by pass by reference and pass by value in Java?

Pass by reference means, passing the address itself rather than passing the value. Pass by value means
passing a copy of the value.

If youre overriding the method equals() of an object, which other method you might also
consider?

hashCode()

What is Byte Code? Or

What gives java its write once and run anywhere nature?

All Java programs are compiled into class files that contain bytecodes. These byte codes can be run in
any platform and hence java is said to be platform independent.

Expain the reason for each keyword of public static void main(String args[])?

public- main(..) is the first method called by java environment when a program is executed so it has to
accessible from java environment. Hence the access specifier has to be public.

static: Java environment should be able to call this method without creating an instance of the class , so
this method must be declared as static.

void: main does not return anything so the return type must be void

The argument String indicates the argument type which is given at the command line and arg is an array
for string given during command line.

y.rajashekher@gmail.com Page 18
What are the differences between == and .equals() ? Or

what is difference between == and equals Or

Difference between == and equals method Or

What would you use to compare two String variables - the operator == or the method equals()? Or

How is it possible for two String objects with identical values not to be equal under the ==
operator?

The == operator compares two objects to determine if they are the same object in memory i.e. present in
the same memory location. It is possible for two String objects to have the same value, but located in
different areas of memory.

== compares references while .equals compares contents. The method public boolean equals(Object obj)
is provided by the Object class and can be overridden. The default implementation returns true only if the
object is compared with itself, which is equivalent to the equality operator == being used to compare
aliases to the object. String, BitSet, Date, and File override the equals() method. For two String objects,
value equality means that they contain the same character sequence. For the Wrapper classes, value
equality means that the primitive values are equal.

public class EqualsTest {

public static void main(String[] args) {

String s1 = abc;
String s2 = s1;
String s5 = abc;
String s3 = new String(abc);
String s4 = new String(abc);
System.out.println(== comparison : + (s1 == s5));
System.out.println(== comparison : + (s1 == s2));
System.out.println(Using equals method : +
s1.equals(s2));
System.out.println(== comparison : + s3 == s4);
System.out.println(Using equals method : +
s3.equals(s4));
}
}

Output
== comparison : true
== comparison : true
Using equals method : true
false
Using equals method : true

What if the static modifier is removed from the signature of the main method? Or

What if I do not provide the String array as the argument to the method?

Program compiles. But at runtime throws an error NoSuchMethodError.

y.rajashekher@gmail.com Page 19
Why oracle Type 4 driver is named as oracle thin driver?

Oracle provides a Type 4 JDBC driver, referred to as the Oracle thin driver. This driver includes its own
implementation of a TCP/IP version of Oracles Net8 written entirely in Java, so it is platform independent,
can be downloaded to a browser at runtime, and does not require any Oracle software on the client side.
This driver requires a TCP/IP listener on the server side, and the client connection string uses the TCP/IP
port address, not the TNSNAMES entry for the database name.

What is the difference between final, finally and finalize? What do you understand by the java final
keyword? Or

What is final, finalize() and finally? Or

What is finalize() method? Or

What is the difference between final, finally and finalize? Or

What does it mean that a class or member is final?

o final - declare constant


o finally - handles exception
o finalize - helps in garbage collection

Variables defined in an interface are implicitly final. A final class cant be extended i.e., final class may not
be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows
the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final
method cant be overridden when its class is inherited. You cant change value of a final variable (is a
constant). finalize() method is used just before an object is destroyed and garbage collected. finally, a key
word used in exception handling and will be executed whether or not an exception is thrown. For
example, closing of open connections is done in the finally method.

What is the Java API?

The Java API is a large collection of ready-made software components that provide many useful
capabilities, such as graphical user interface (GUI) widgets.

What is the GregorianCalendar class?

The GregorianCalendar provides support for traditional Western calendars.

What is the ResourceBundle class?

The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to
tailor the programs appearance to the particular locale in which it is being run.

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.

y.rajashekher@gmail.com Page 20
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();

Or u can use Integer.parseInt method

String numString = 1000;

int id = Integer.parseInt(numString);

What is the SimpleTimeZone class?

The SimpleTimeZone class provides support for a Gregorian calendar.

What is the difference between a while statement and a do statement?

A while statement (pre test) checks at the beginning of a loop to see whether the next loop iteration
should occur. A do while statement (post test) checks at the end of a loop to see whether the next
iteration of a loop should occur. The do statement will always execute the loop body at least once.

What is the Locale class?

The Locale class is used to tailor a program output to the conventions of a particular geographic, political,
or cultural region.

Describe the principles of OOPS.

There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.

Polymorphism is the capability of an action or method to do different things based on the object that it is
acting upon. This is the third basic principle of object oriented programming. Overloading and overriding
are two types of polymorphism

Explain the Encapsulation principle.

Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a
single entity. This keeps the data safe from outside interface and misuse. Objects allow procedures to be
encapsulated with their data to reduce potential interference. One way to think about encapsulation is as
a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined
outside the wrapper.

Encapsulation is the concept that an object should totally separate its interface from its implementation.
All the data and implementation code for an object should be entirely hidden behind its interface.

What is data encapsulation?

Encapsulation may be used by creating get and set methods in a class (JAVABEAN) which are used to
access the fields of the object. Typically the fields are made private while the get and set methods are
public. Encapsulation can be used to validate the data that is to be stored, to do calculations on data that
is stored in a field or fields, or for use in introspection (often the case when using javabeans in Struts, for

y.rajashekher@gmail.com Page 21
instance). Wrapping of data and function into a single unit is called as data encapsulation. Encapsulation
is nothing but wrapping up the data and associated methods into a single unit in such a way that data can
be accessed with the help of associated methods. Encapsulation provides data security. It is nothing but
data hiding.

Explain the Inheritance principle.

Inheritance is the process by which one object acquires the properties of another object. Inheritance
allows well-tested procedures to be reused and enables changes to make once and have effect in all
relevant places

What are Encapsulation, Inheritance and Polymorphism Or

Explain the Polymorphism principle. Explain the different forms of Polymorphism.

Polymorphism in simple terms means one name many forms. Polymorphism enables one entity to be
used as a general category for different types of actions. The specific action is determined by the exact
nature of the situation.

Polymorphism exists in three distinct forms in Java:


Method overloading
Method overriding through inheritance
Method overriding through the Java interface

What do you understand by casting in java language? What are the types of casting?

The process of converting one data type to another is called Casting. There are two types of casting in
Java; these are implicit casting and explicit casting.

What is implicit casting?

Implicit casting is the process of simply assigning one entity to another without any transformation
guidance to the compiler. This type of casting is not permitted in all kinds of transformations and may not
work for all scenarios.

Example

int i = 1000;

long j = i; //Implicit casting

What is explicit casting?

Explicit casting in the process in which the complier are specifically informed to about transforming the
object.

Example

long i = 700.20;

int j = (int) i; //Explicit casting

y.rajashekher@gmail.com Page 22
Is sizeof a keyword in java?

The sizeof operator is not a keyword in java.

What is a native method?

A native method is a method that is implemented in a language other than Java.

In System.out.println(), what is System, out and println?

System is a predefined final class, out is a PrintStream object and println is a built-in overloaded method
in the out object.

What is the Java Virtual Machine (JVM)?

The Java Virtual Machine is software that can be ported onto various hardware-based platforms

What do you understand by downcasting?

The process of Downcasting refers to the casting from a general to a more specific type, i.e. casting down
the hierarchy (for example casting an object from Animal to Dog)

What are Java Access Specifiers? Or

What is the difference between public, private, protected and default Access Specifiers? Or

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 all the subclasses and classes which are in the same package.
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

Which class is the superclass of every class?

Object is the super class for all classes.( It is also called as the Cosmic super class.)

Name primitive Java types.

The 8 primitive types are byte, char, short, int, long, float, double, and boolean.

What is the difference between static and non-static variables? Or

What are class variables? Or

What is static in java? Or

What is a static method?

y.rajashekher@gmail.com Page 23
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 doesnt 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
cant override a static method with a non-static method. In other words, you cant change a static method
into an instance method in a subclass.

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

What is the difference between the boolean & operator and the && operator?

If an expression involving the boolean & operator is evaluated, both operands are evaluated, whereas the
&& operator is a short cut operator. 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. If
the first operand evaluates to false, the evaluation of the second operand is skipped.

How does Java handle integer overflows and underflows?

It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

What if I write static public void instead of public static void?

Program compiles and runs properly.

What is the difference between declaring a variable and defining a variable?

In declaration we only mention the type of the variable and its name without initializing it. Defining means
declaration + initialization. E.g. String s; is just a declaration while String s = new String (bob); Or String
s = bob; are both definitions.

What type of parameter passing does Java support?

In Java the arguments (primitives and objects) are always passed 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 do you understand by a variable?

Variable is a named memory location that can be easily referred in the program. The variable is used to
hold the data and it can be changed during the course of the execution of the program.

What do you understand by numeric promotion?

y.rajashekher@gmail.com Page 24
The Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that
integral and floating-point operations may take place. In the numerical promotion process the byte, char,
and short values are converted to int values. The int values are also converted to long values, if
necessary. The long and float values are converted to double values, as required.

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.

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.

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.

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

Can I have multiple main methods in the same class?

We can have multiple overloaded main methods but there can be only one main method with the
following signature :

public static void main(String[] args) {}

If it is having the same signature(given above) for more than one method the program fails to compile.
The compiler says that the main method is already defined in the class.

Explain working of Java Virtual Machine (JVM)?

JVM is an abstract computing machine like any other real computing machine which first converts .java
file into .class file by using Compiler (.class is nothing but byte code file.) and Interpreter reads byte
codes.

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

y.rajashekher@gmail.com Page 25
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;

An other approach to the same question

You use an XOR swap.

for example:

int a = 5; int b = 10;


a = a ^ b;
b = a ^ b;
a = a ^ b;

What is reflection API? How are they implemented?

Reflection is the process of introspecting the features and state of a class at runtime and dynamically
manipulate at run time. This is supported using Reflection API with built-in classes like Class, Method,
Fields, Constructors etc. Example: Using Java Reflection API we can get the class name, by using the
getName method.

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.

What is phantom memory?

Phantom memory is false memory. Memory that does not exist in reality.

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

What is difference between String and StringTokenizer?

A StringTokenizer is utility class used to break up string.

Example:

StringTokenizer st = new StringTokenizer(Hello World);

while (st.hasMoreTokens()) {

y.rajashekher@gmail.com Page 26
System.out.println(st.nextToken());

Output:

Hello

World

Q: What is the difference between an Interface and an Abstract class?


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

Q: What is the purpose of garbage collection in Java, and when is it used?


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

Q: Describe synchronization in respect to multithreading.


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

Q: Explain different way of creating a thread?


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

Q: What are pass by reference and passby value?


A: Pass By Reference means the passing the address itself rather than passing the value.
Passby Value means passing a copy of the value to be passed.

Q: What is HashMap and Map?


A: Map is Interface and Hashmap is class that implements that.

Q: Difference between HashMap and HashTable?


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

y.rajashekher@gmail.com Page 27
Q: Difference between Vector and ArrayList?
A: Vector is synchronized whereas arraylist is not.

Q: Difference between Swing and Awt?


A: AWT are heavy-weight componenets. Swings are light-weight components. Hence swing
works faster than AWT.

Q: What is the difference between a constructor and a method?


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

Q: What is an Iterator?
A: Some of the collection classes provide traversal of their contents via a java.util.Iterator
interface. This interface allows you to walk through a collection of objects, operating on
each object in turn. Remember when using Iterators that they contain a snapshot of the
collection at the time the Iterator was obtained; generally it is not advisable to modify
the collection itself while traversing an Iterator.

Q: State the significance of public, private, protected, default modifiers both singly
and in combination and state the effect of package relationships on declared
items qualified by these modifiers.
A: public : Public class is visible in other packages, field is visible everywhere (class must
be public too)
private : Private variables or methods may be used only by an instance of the same
class that declares the variable or method, A private feature may only be accessed by the
class that owns the feature.
protected : Is available to all classes in the same package and also available to all
subclasses of the class that owns the protected feature.This access is provided even to
subclasses that reside in a different package from the class that owns the protected
feature.
default :What you get by default ie, without any access modifier (ie, public private or
protected).It means that it is visible to all within a particular package.

Q: What is an abstract class?


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

Q: What is static in java?


A: 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

y.rajashekher@gmail.com Page 28
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.

Q: What is final?
A: A final class can't be extended ie., final class may not be subclassed. A final method can't
be overridden when its class is inherited. You can't change value of a final variable (is a
constant).

Q: If I do not provide any arguments on the command line, then the String array of
Main method will be empty or null?
A: It is empty. But not null.

Q: What environment variables do I need to set on my machine in order to be able


to run Java programs?
A: CLASSPATH and PATH are the two variables.

Q: Can I have multiple main methods in the same class?


A: No the program fails to compile. The compiler says that the main method is already
defined in the class.

Q: Do I need to import java.lang package any time? Why ?


A: No. It is by default loaded internally by the JVM.

Q: Can I import same package/class twice? Will the JVM load the package twice at
runtime?
A: One can import the same package or same class multiple times. Neither compiler nor JVM
complains abt it. And the JVM will internally load the class only once no matter how many
times you import the same class.

Q: What are Checked and UnChecked Exception?


A: 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. eg, 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. eg, 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.

Q: What is Overriding?

y.rajashekher@gmail.com Page 29
A: 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.

Q: What are different types of inner classes?


A: Nested top-level classes, Member classes, Local classes, Anonymous classes

Nested top-level classes- If you declare a class within a class and specify the static
modifier, the compiler treats the class just like any other top-level class.
Any class outside the declaring class accesses the nested class with the declaring class
name acting similarly to a package. eg, outer.inner. Top-level inner classes implicitly
have access only to static variables.There can also be inner interfaces. All of these are of
the nested top-level variety.

Member classes - Member inner classes are just like other member methods and
member variables and access to the member class is restricted, just like methods and
variables. This means a public member class acts similarly to a nested top-level class.
The primary difference between member classes and nested top-level classes is that
member classes have access to the specific instance of the enclosing class.

Local classes - Local classes are like local variables, specific to a block of code. Their
visibility is only within the block of their declaration. In order for the class to be useful
beyond the declaration block, it would need to implement a
more publicly available interface. Because local classes are not members, the modifiers
public, protected, private, and static are not usable.

Anonymous classes - Anonymous inner classes extend local inner classes one level
further. As anonymous classes have no name, you cannot provide a constructor.

Q: Are the imports checked for validity at compile time? e.g. will the code
containing an import such as java.lang.ABCD compile?
A: Yes the imports are checked for the semantic validity at compile time. The code
containing above line of import will not compile. It will throw an error saying, cannot
resolve symbol
symbol : class ABCD
location: package io
import java.io.ABCD;

Q: Does importing a package imports the subpackages as well? e.g. Does importing
com.MyTest.* also import com.MyTest.UnitTests.*?
A: No you will have to import the subpackages explicitly. Importing com.MyTest.* will
import classes in the package MyTest only. It will not import any class in any of it's
subpackage.

y.rajashekher@gmail.com Page 30
Q: What is the default value of an object reference declared as an instance
variable?
A: null unless we define it explicitly.

Q: Can a top level class be private or protected?


A: No. A top level class cannot be private or protected. It can have either "public" or no
modifier. If it does not have a modifier it is supposed to have a default access. If a top
level class is declared as private the compiler will complain that the "modifier private is
not allowed here". This means that a top level class cannot be private. Same is the case
with protected.

Q: What type of parameter passing does Java support?


A: In Java the arguments are always passed by value

Q: Primitive data types are passed by reference or pass by value?


A: Primitive data types are passed by value.

Q: Objects are passed by value or by reference?


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

Q: What is serialization?
A: Serialization is a mechanism by which you can save the state of an object by converting it
to a byte stream.

Q: How do I serialize an object to a file?


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

Q: Which methods of Serializable interface should I implement?


A: The serializable interface is an empty interface, it does not contain any methods. So we
do not implement any methods. (An interface which doesnt have any method is called as
the Marker Interface)

Q: How can I customize the seralization process? i.e. how can one have a control
over the serialization process?
A: Yes it is possible to have control over serialization process. The class should implement
Externalizable interface. This interface contains two methods namely readExternal and
writeExternal. You should implement these methods and write the logic for customizing
the serialization process.

Q: What is the common usage of serialization?


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

Q: What is Externalizable interface?


A: 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

y.rajashekher@gmail.com Page 31
these methods.

Q: When you serialize an object, what happens to the object references included in
the object?
A: The serialization mechanism generates an object graph for serialization. Thus it
determines whether the included object references are serializable or not. This is a
recursive process. Thus when an object is serialized, all the included objects are also
serialized alongwith the original obect. (Here all the included objects should also be
serialized)

Q: What one should take care of while serializing the object?


A: One should make sure that all the included objects are also serializable. If any of the
objects is not serializable then it throws a NotSerializableException.

Q: What happens to the static fields of a class during serialization?


A: There are three exceptions in which serialization doesnot necessarily read and write to
the stream. These are
1. Serialization ignores static fields, because they are not part of ay particular state state.
2. Base class fields are only hendled if the base class itself is serializable.
3. Transient fields.
Q: Does Java provide any construct to find out the size of an object?
A: No there is not sizeof operator in Java. So there is not direct way to determine the size of
an object directly in Java.

Q: Give a simplest way to find out the time a method takes for execution without
using any profiling tool?
A: Read the system time just before the method is invoked and immediately after method
returns. Take the time difference, which will give you the time taken by a method for
execution.

To put it in code...

long start = System.currentTimeMillis ();


method ();
long end = System.currentTimeMillis ();

System.out.println ("Time taken for execution is " + (end - start));

Remember that if the time taken for execution is too small, it might show that it is taking
zero milliseconds for execution. Try it on a method which is big enough, in the sense the
one which is doing considerable amount of processing.

Q: What are wrapper classes?


A: Java provides specialized classes corresponding to each of the primitive data types. These
are called wrapper classes. They are e.g. Integer, Character, Double etc.

Q: Why do we need wrapper classes?


A: It is sometimes easier to deal with primitives as objects. Moreover most of the collection
classes store objects and not primitive data types(this is before 1.5, in 1.5 u can store
primitives also in collection classes). And also the wrapper classes provide many utility
methods also. Because of these reasons we need wrapper classes. And since we create

y.rajashekher@gmail.com Page 32
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.

Q: What are checked exceptions?


A: Checked exceptionare those which the Java compiler forces you to catch by using try
catch or by declaring as throws in the method signature. e.g. IOException are checked
Exceptions.

Q: What are runtime exceptions?


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

Q: What is the difference between error and an exception?


A: 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. e.g. FileNotFoundException will be thrown
if the specified file does not exist. Or a NullPointerException 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.).

Q: How to create custom exceptions?


A: Your class should extend class Exception, or some more specific type thereof (that is sub
class of Exception class).

Q: If I want an object of my class to be thrown as an exception object, what should


I do?
A: The class should extend from Exception class. Or you can extend your class from some
more precise exception type also (that is sub class of Exception class).

Q: If my class already extends from some other class what should I do if I want an
instance of my class to be thrown as an exception object?
A: One cannot do anything in this scenario. Because Java does not allow multiple inheritance
and does not provide any exception interface as well.

Q: How does a try statement determine which catch clause should be used to
handle an exception?
A: 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 exceptions executed. The remaining catch clauses are ignored.

Q: How does an exception permeate through the code?


A: An unhandled exception moves up the method stack in search of a matching. When an
exception is thrown from a code which is wrapped in a try block followed by one or more
catch blocks, a search is made for matching catch block. If a matching type is found then
that block will be invoked. If a matching type is not found then the exception moves up
the method stack and reaches the caller method. Same procedure is repeated if the caller
method is included in a try catch block. This process continues until a catch block
handling the appropriate type of exception is found. If it does not find such a block then
finally the program terminates.

y.rajashekher@gmail.com Page 33
Q: What are the different ways to handle exceptions?
A: There are two ways to handle exceptions,
1. By wrapping the desired code in a try block followed by a catch block to catch the
exceptions. and
2. List the desired exceptions in the throws clause of the method and let the caller of the
method hadle those exceptions.

Q: What is the basic difference between the 2 approaches to exception handling.


1> try catch block and
2> specifying the candidate exceptions in the throws clause?
When should you use which approach?
A: In the first approach as a programmer of the method, you urself are dealing with the
exception. This is fine if you are in a best position to decide should be done in case of an
exception. Whereas if it is not the responsibility of the method to deal with its own
exceptions, then do not use this approach. In this case use the second approach. In the
second approach we are forcing the caller of the method to catch the exceptions that the
method is likely to throw. This is often the approach library creators use. They list the
exception in the throws clause and we must catch them. You will find the same approach
throughout the java libraries we use.

Q: Is it necessary that each try block must be followed by a catch block?


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

Q: If I write return at the end of the try block, will the finally block still execute?
A: Yes even if you write return as the last statement in the try block and no exception
occurs, the finally block will execute. The finally block will execute and then the control
return.

Q: If I write System.exit (0); at the end of the try block, will the finally block still
execute?
A: 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 block never executes.

Q: How are Observer and Observable used?


A: Objects that subclass the Observable class maintain a list of observers. When an
Observable object is updated it invokes the update() method of each of its observers to
notify the observers that it has changed state. The Observer interface is implemented by
objects that observe Observable objects.

Q: What is synchronization and why is it important?


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

Q: How does Java handle integer overflows and underflows?


A: It uses those low order bytes of the result that can fit into the size of the type allowed by
the operation.

y.rajashekher@gmail.com Page 34
Q: Does garbage collection guarantee that a program will not run out of memory?
A: Garbage collection does not guarantee that a program will not run out of memory. It is
possible for programs to use up memory resources faster than they are garbage
collected. It is also possible for programs to create objects that are not subject to
garbage collection.

Q: What is the difference between preemptive scheduling and time slicing?


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

Q: When a thread is created and started, what is its initial state?


A: A thread is in the ready state after it has been created and started.

Q: What is the purpose of finalization?


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

Q: What is the Locale class?


A: The Locale class is used to tailor program output to the conventions of a particular
geographic, political, or cultural region.

Q: What is the difference between a while statement and a do statement?


A: A while statement checks at the beginning of a loop to see whether the next loop
iteration should occur. A do statement checks at the end of a loop to see whether the
next iteration of a loop should occur. The do statement will always execute the body of a
loop at least once.

Q: What is the difference between static and non-static variables?


A: A static variable is associated with the class as a whole rather than with specific instances
of a class. Non-static variables take on unique values with each object instance.

Q: How are this() and super() used with constructors?


A: This() is used to invoke a constructor of the same class. super() is used to invoke a
superclass constructor.

Q: What are synchronized methods and synchronized statements?

y.rajashekher@gmail.com Page 35
A: 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.

Q: What is daemon thread and which method is used to create the daemon thread?
A: 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.

Q: Can applets communicate with each other?


A: At this point in time applets may communicate with other applets running in the same
virtual machine. If the applets are of the same class, they can communicate via shared
static variables. If the applets are of different classes, then each will need a reference to
the same class with static variables. In any case the basic idea is to pass the information
back and forth through a static variable.

An applet can also get references to all other applets on the same page using the
getApplets() method of java.applet.AppletContext. Once you get the reference to an
applet, you can communicate with it by using its public members.

It is conceivable to have applets in different virtual machines that talk to a server


somewhere on the Internet and store any data that needs to be serialized there. Then,
when another applet needs this data, it could connect to this same server. Implementing
this is non-trivial.

Q: What are the steps in the JDBC connection?


A: 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();

y.rajashekher@gmail.com Page 36
Q: Can an unreachable object become reachable again?
A: An unreachable object may become reachable again. This can happen when the object's
finalize() method is invoked and the object performs an operation which causes it to
become accessible to reachable objects.

Q: What method must be implemented by all threads?


A: All tasks must implement the run() method, whether they are a subclass of Thread or
implement the Runnable interface.

Q: What are synchronized methods and synchronized statements?


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

Q: What is Externalizable?
A: Externalizable is an Interface that extends Serializable Interface. And sends data into
Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and
readExternal(ObjectInput in)

Q: What modifiers are allowed for methods in an Interface?


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

Q: What are some alternatives to inheritance?


A: Delegation is an alternative to inheritance. Delegation means that you include an
instance of another class as an instance variable, and forward messages to the instance.
It is often safer than inheritance because it forces you to think about each message you
forward, because the instance is of a known class, rather than a new class, and because
it doesn't force you to accept all the methods of the super class: you can provide only the
methods that really make sense. On the other hand, it makes you write more code, and
it is harder to re-use (because it is not a subclass).

Q: What does it mean that a method or field is "static"?


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

y.rajashekher@gmail.com Page 37
Q: What is the difference between preemptive scheduling and time slicing?
A: 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.

Q: What is the catch or declare rule for method declarations?


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

Q: Is Empty .java file a valid source file?


A: Yes, an empty .java file is a perfectly valid source file.

Q: Can a .java file contain more than one java classes?


A: Yes, a .java file contain more than one java classes, provided at the most one of them is
a public class.

Q: Is String a primitive data type in Java?


A: No String is not a primitive data type in Java, even though it is one of the most
extensively used object. Strings in Java are instances of String class defined in java.lang
package.

Q: Is main a keyword in Java?


A: No, main is not a keyword in Java.

Q: Is next a keyword in Java?


A: No, next is not a keyword.

Q: Is delete a keyword in Java?


A: No, delete is not a keyword in Java. Java does not make use of explicit destructors the
way C++ does.

Q: Is exit a keyword in Java?


A: No. To exit a program explicitly you use exit method in System object.

Q: What happens if you dont initialize an instance variable of any of the primitive
types in Java?
A: Java by default initializes it to the default value for that primitive type. Thus an int will be
initialized to 0, a boolean will be initialized to false.

Q: What will be the initial value of an object reference which is defined as an

y.rajashekher@gmail.com Page 38
instance variable?
A: The object references are all initialized to null in Java. However in order to do anything
useful with these references, you must set them to a valid object, else you will get
NullPointerExceptions everywhere you try to use such default initialized references.

Q: What are the different scopes for Java variables?


A: 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.
1. 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.
2. 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.
3. 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.

Q: What is the default value of the local variables?


A: The local variables are not initialized to any default value, neither primitives nor object
references. If you try to use these variables without initializing them explicitly, the java
compiler will not compile the code. It will complain abt the local varaible not being
initilized..

Q: How many objects are created in the following piece of code?


MyClass c1, c2, c3;
c1 = new MyClass ();
c3 = new MyClass ();
A: Only 2 objects are created, c1 and c3. The reference c2 is only declared and not
initialized.

Q: Can a public class MyClass be defined in a source file named YourClass.java?


A: No the source file name, if it contains a public class, must be the same as the public class
name itself with a .java extension.

Q: Can main method be declared final?


A: Yes, the main method can be declared final, in addition to being public static.

Q: What will be the output of the following statement?


System.out.println ("1" + 3);
A: It will print 13.

Q: What will be the default values of all the elements of an array defined as an

y.rajashekher@gmail.com Page 39
instance variable?
A: If the array is an array of primitive types, then all the elements of the array will be
initialized to the default value corresponding to that primitive type. e.g. All the elements
of an array of int will be initialized to 0, while that of boolean type will be initialized to
false. Whereas if the array is an array of references (of any type), all the elements will be
initialized to null.

========================== ***************** =========================


Java Packages Interview Questions

Q: Do I need to import java.lang package any time? Why? Or

Which package is always imported by default?

No. It is by default loaded internally by the JVM. The java.lang package is always imported by default.

Q: Can I import same package/class twice? Will the JVM load the package twice at runtime?

One can import the same package or same class multiple times. Neither compiler nor JVM complains
anything about it. And the JVM will internally load the class only once no matter how many times you
import the same class.

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

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

Q: What is a Java package and how is it used? Or

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

Q: Are the imports checked for validity at compile time? e.g. will the code containing an import
such as java.lang.BOB compile?

Yes the imports are checked for the semantic validity at compile time. The code containing above line of
import will not compile. It will throw an error saying, cannot resolve symbol.

If you think that an important java interview question is missing or some answers are wrong in the site

========================== ***************** =========================


Java Classes and Objects Interview Questions

y.rajashekher@gmail.com Page 40
Q: What restrictions are placed on method overloading?

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

Q: What is the difference between String and StringBuffer?

String objects are immutable whereas StringBuffer objects are not. StringBuffer unlike Strings support
growable and modifiable strings.

Q: Can a private method of a superclass be declared within a subclass?

Sure. A private field or method or inner class belongs to its declared class and hides from its subclasses.
There is no way for private stuff to have a runtime overloading or overriding (polymorphism) features.

Q: What is the default value of an object reference declared as an instance variable?

null unless we define it explicitly.

Q: What is the difference between a constructor and a method? Or

Q: 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 subclasss constructor.

Q: Can a top-level class be private or protected?

No. A top-level class cannot be private or protected. It can have either public or no modifier. If it does
not have a modifier it is supposed to have a default access. If a top level class is declared as
private/protected the compiler will complain that the modifier private is not allowed here.

Q: Why Java does not support multiple inheritance?

Java does support multiple inheritance via interface implementation.

Q: Where and how can you use a private constructor?

Private constructor can be used if you do not want any other class to instantiate the class. This concept is
generally used in Singleton Design Pattern. The instantiation of such classes is done from a static public
method.

Q: How are this() and super() used with constructors?

y.rajashekher@gmail.com Page 41
this() is used to invoke a constructor of the same class. super() is used to invoke a superclass
constructor.

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

Q: What are the Object and Class classes used for? Which class should you use to obtain design
information about an object? or

Q: 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 objects design. A Class is only a definition or prototype of real life object. Whereas
an 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.

Q: What is a singleton class? Or

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

Q: What is method overloading and method overriding? Or

Q: 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

y.rajashekher@gmail.com Page 42
Q: If a class is declared without any access modifiers, where may the class be accessed?

A class that is declared without any access modifiers is said to have package or default access. This
means that the class can only be accessed by other classes and interfaces that are defined within the
same package.

Q: Does a class inherit the constructors of its superclass?

A class does not inherit constructors from any of its super classes.

Q: Can an objects finalize() method be invoked while it is reachable?

An objects finalize() method cannot be invoked by the garbage collector while the object is still reachable.
However, an objects finalize() method may be invoked by other objects.

Q: What is the purpose of the Runtime class?

The purpose of the Runtime class is to provide access to the Java runtime system.

It returns the runtime information like memory availability.

* Runtime.freeMemory() > Returns JVM Free Memory


* Runtime.maxMemory() > Returns the maximum amount of memory that the JVM will attempt to use. It
also helps to run the garbage collector
* Runtime.gc()

Q: What is the purpose of the System class?

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

Q: Can an unreachable object become reachable again?

An unreachable object may become reachable again. This can happen when the objects finalize()
method is invoked and the object performs an operation which causes it to become accessible to
reachable object.

Q: 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 get methods. It could be used within a JSP using
JSP tags to use them.

Q: What is the functionality of instanceOf() ?


instanceOf opertaor is used to check whether an object can be cast to a specific type without throwing
ClassCastException.

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

y.rajashekher@gmail.com Page 43
Q: I want to create two instances of a class ,But when trying for creating third instance it should
not allow me to create . What i have to do for making this?

One way of doing this would be:

public class test1

static int cntr=0;

test1()

{ cntr++;

if(cntr>2)

throw new NullPointerException();//u can define a new exception // for this

public static void main(String args[])

test1 t1= new test1();

System.out.println(hello 1);

test1 t2= new test1();

System.out.println(hello 2);

test1 t3= new test1();

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

Q: What is heap in Java?

y.rajashekher@gmail.com Page 44
It is a memory area which stores all the objects created by an executing program.

Q: Why default constructor of base class will be called first in java?

A subclass inherits all the methods and fields (eligible one) from the base class, so base class is
constructed in the process of creation of subclass object (subclass is also an object of superclass). Hence
before initializing the default value of sub class the super class should be initialized using the default
constructor.

Q: 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

Q: 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

========================== ***************** =========================


Java Abstract Class and Interface Interview Questions

Q: What is the difference between Abstract class and Interface Or


Q: When should you use an abstract class, when an interface, when both? Or
Q: What is similarities/difference between an Abstract class and Interface? Or
Q: What is the difference between interface and an abstract class?

1. Abstract class is a class which contain one or more abstract methods, which has to be implemented by
sub classes. An abstract class can contain no abstract methods also i.e. abstract class may contain
concrete methods. A Java Interface can contain only method declarations and public static final constants
and doesnt contain their implementation. The classes which implement the Interface must provide the
method definition for all the methods present.

2. Abstract class definition begins with the keyword abstract keyword followed by Class definition. An
Interface definition begins with the keyword interface.

y.rajashekher@gmail.com Page 45
3. Abstract classes are useful in a situation when some general methods should be implemented and
specialization behavior should be implemented by subclasses. Interfaces are useful in a situation when all
its properties need to be implemented by subclasses

4. All variables in an Interface are by default - public static final while an abstract class can have instance
variables.

5. An interface is also used in situations when a class needs to extend an other class apart from the
abstract class. In such situations its not possible to have multiple inheritance of classes. An interface on
the other hand can be used when it is required to implement one or more interfaces. Abstract class does
not support Multiple Inheritance whereas an Interface supports multiple Inheritance.

6. An Interface can only have public members whereas an abstract class can contain private as well as
protected members.

7. A class implementing an interface must implement all of the methods defined in the interface, while a
class extending an abstract class need not implement any of the methods defined in the abstract class.

8. The problem with an interface is, if you want to add a new feature (method) in its contract, then you
MUST implement those method in all of the classes which implement that interface. However, in the case
of an abstract class, the method can be simply implemented in the abstract class and the same can be
called by its subclass

9. Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class.
Abstract classes are fast

10.Interfaces are often used to describe the peripheral abilities of a class, and not its central identity, E.g.
an Automobile class might
implement the Recyclable interface, which could apply to many otherwise totally unrelated objects.

Note: There is no difference between a fully abstract class (all methods declared as abstract and all fields
are public static final) and an interface.

Note: If the various objects are all of-a-kind, and share a common state and behavior, then tend towards a
common base class. If all they
share is a set of method signatures, then tend towards an interface.

Similarities:
Neither Abstract classes nor Interface can be instantiated.

Q: What does it mean that a method or class is abstract?

An abstract class cannot be instantiated. Only its subclasses can be instantiated. A class that has one or
more abstract methods must be declared abstract. A subclass that does not provide an implementation
for its inherited abstract methods must also be declared abstract. You indicate that a class is abstract with
the abstract keyword like this:

public abstract class AbstractClass

Abstract classes may contain abstract methods. A method declared abstract is not actually implemented
in the class. It exists only to be overridden in subclasses. Abstract methods may only be included in
abstract classes. However, an abstract class is not required to have any abstract methods, though most
of them do. Each subclass of an abstract class must override the abstract methods of its superclasses

y.rajashekher@gmail.com Page 46
or itself be declared abstract. Only the methods prototype is provided in the class definition. Also, a final
method can not be abstract and vice versa. Methods specified in an interface are implicitly abstract.
. It has no body. For example,

public abstract float getInfo()

Q: What must a class do to implement an interface?

The class must provide all of the methods in the interface and identify the interface in its implements
clause.

Q: What is an abstract method?

An abstract method is a method whose implementation is deferred to a subclass.

Q: What is a marker interface & What is a cloneable interface and how many methods does
it contain?

Interfaces with empty bodies are called marker interfaces having certain property or behavior.
Examples:java.lang.Cloneable,java.io.Serializable,java.util.EventListener.

Q: What is interface? How to support multiple inhertance in Java?

An Interface are implicitly abstract and public. An interface body can contain constant declarations,
method prototype declarations, nested class declarations, and nested interface d Interfaces provide
support for multiple inheritance in Java. A class that implements the interfaces is bound to implement all
the methods defined in Interface.
Example of Interface:
public interface sampleInterface {
public void functionOne();

public long CONSTANT_ONE = 1000;


}

Q: What is an abstract class? Or


Q: Can you make an instance of an abstract class?

Abstract classes can contain abstract and concrete methods. Abstract classes cannot be instantiated
directly i.e. we cannot call the constructor of an abstract class directly nor we can create an instance of an
abstract class by using Class.forName().newInstance() (Here we get java.lang.InstantiationException).
However, if we create an instance of a class that extends an Abstract class, compiler will initialize both
the classes. Here compiler will implicitly call the constructor of the Abstract class. Any class that contain
an abstract method must be declared abstract and abstract methods can have definitions only in child
classes. By overriding and customizing the abstract methods in more than one subclass makes
Polymorphism and through Inheritance we define body to the abstract methods. Basically an abstract
class serves as a template. Abstract class must be extended/subclassed for it to be implemented. A class
may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.
Abstract class is a class that provides some general functionality but leaves specific implementation to its
inheriting classes.

Example of Abstract class:

y.rajashekher@gmail.com Page 47
abstract class AbstractClassExample{

protected String name;


public String getname() {
return name;
}
public abstract void function();
}

Example: Vehicle is an abstract class and Bus Truck, car etc are specific implementations

No! You cannot make an instance of an abstract class. An abstract class has to be sub-classed.
If you have an abstract class and you want to use a method which has been implemented, you may
need to subclass that abstract class, instantiate your subclass and then call that method.

Q: What is meant by Abstract Interface?

Firstly, an interface is abstract. That means you cannot have any implementation in an interface.
All the methods declared in an interface are abstract methods or signatures of the methods.

Q: How to define an Interface?

In Java Interface defines the methods but does not implement them. Interface can include constants.
A class that implements the interfaces is bound to implement all the methods defined in Interface.
Example of Interface:

public interface SampleInterface {


public void functionOne();

public long CONSTANT_ONE = 1000;


}

Q: Can Abstract Class have constructors? Can interfaces have constructors?

Abstract classs can have a constructor, but you cannot access it through the object, since you cannot
instantiate abstract class. To access the constructor create a sub class and extend the abstract class
which is having the constructor. Interfaces cannot have constructors.

Example
public abstract class AbstractExample {
public AbstractExample(){
System.out.println(In AbstractExample());
}
}

public class Test extends AbstractExample{


public static void main(String args[]){
Test obj=new Test();
}
}

Q: If interface & abstract class have same methods and those methods contain no
implementation, which one would you prefer?

y.rajashekher@gmail.com Page 48
Obviously one should ideally go for an interface, as we can only extend one class. Implementing an
interface for a class is very much effective rather than extending an abstract class because we can
extend some other useful class for this subclass

========================== ***************** =========================


Java Garbage Collection Interview Questions

Q: Explain garbage collection? Or

Q: How you can force the garbage collection? Or

Q: What is the purpose of garbage collection in Java, and when is it used? Or

Q: What is Garbage Collection and how to call it explicitly? Or

Q: 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 cant be forced. There is no guarantee that Garbage collection will start
immediately upon request of System.gc().

Q: What kind of thread is the Garbage collector thread?

It is a daemon thread.

Q: Can an objects finalize() method be invoked while it is reachable?

An objects finalize() method cannot be invoked by the garbage collector while the object is still reachable.
However, an objects finalize() method may be invoked by other objects.

Q: Does garbage collection guarantee that a program will not run out of memory?

Garbage collection does not guarantee that a program will not run out of memory. It is possible for
programs to use up memory resources faster than they are garbage collected. It is also possible for
programs to create objects that are not subject to garbage collection.

Q: What is the purpose of finalization?

The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup,
before the object gets garbage collected. For example, closing an opened database Connection.

y.rajashekher@gmail.com Page 49
Q: If an object is garbage collected, can it become reachable again?

Once an object is garbage collected, It can no longer become reachable again.

========================== ***************** =========================


Java Object Serialization Interview Questions

Q: How many methods in the Serializable interface? Which methods of Serializable interface
should I implement?

There is no method in the Serializable interface. Its 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.

Q: What is the difference between Serializalble and Externalizable interface? How can you
control over the serialization process i.e. how can you customize the seralization process?

When you use Serializable interface, your class is serialized automatically by default. But you can
override writeObject() and readObject() two methods to control more complex object serailization process.
When you use Externalizable interface, you have a complete control over your classs serialization
process. This interface contains two methods namely readExternal and writeExternal. You should
implement these methods and write the logic for customizing the serialization process.

Q: How to make a class or a bean serializable? How do I serialize an object to a file? Or

Q: What interface must an object implement before it can be written to a stream as an object?

An object must implement the Serializable or Externalizable interface before it can be written to a stream
as an object. 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.

Q: What happens to the object references included in the object?

The serialization mechanism generates an object graph for serialization. Thus it determines whether the
included object references are serializable or not. This is a recursive process. Thus when an object is
serialized, all the included objects are also serialized alongwith the original object.

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

Q: Common Usage of serialization.

Whenever an object is to be sent over the network or saved in a file, objects are serialized.

y.rajashekher@gmail.com Page 50
Q: What happens to the static fields of a class during serialization?

There are three exceptions in which serialization doesnt necessarily read and write to the stream. These
are
1. Serialization ignores static fields, because they are not part of any particular state.
2. Base class fields are only handled if the base class itself is serializable.
3. Transient fields.

Q: What one should take care of while serializing the object?

One should make sure that all the included objects are also serializable. If any of the objects is not
serializable then it throws a NotSerializableException.

Q: What is a transient variable? Or

Q: Explain the usage of the keyword transient? Or

Q: What are Transient and Volatile Modifiers

A transient variable is a variable that may not be serialized i.e. the value of the variable cant be written to
the stream in a Serializable class. If you dont 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.

Q: What is Serialization and deserialization?

Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process
of restoring these objects.

Q: What is Externalizable?

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.

========================== ***************** =========================


Java Exceptions Questions

Q: Explain the user defined Exceptions?

User defined Exceptions are custom Exception classes defined by the user for specific purpose. A user
defined exception can be created by simply sub-classing an Exception class or a subclass of an
Exception class. This allows custom exceptions to be generated (using throw clause) and caught in the
same way as normal exceptions.
Example:

y.rajashekher@gmail.com Page 51
class CustomException extends Exception {

Q: What classes of exceptions may be caught by a catch clause?

A catch clause can catch any exception that may be assigned to the Throwable type. This includes the
Error and Exception types. Errors are generally irrecoverable conditions

Q: What is the difference between exception and error?

Errors are irrecoverable exceptions. Usually a program terminates when an error is encountered.

Q: What is the difference between throw and throws keywords?

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.

Q: What class of exceptions are generated by the Java run-time system?

Q: The Java runtime system generates Runtime Exceptions and Errors.

Q: What is the base class for Error and Exception?

Throwable

Q: What are Checked and Unchecked Exceptions?

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 exception may be thrown. Checked exceptions must be caught at compile time. Example:
IOException.
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses
also are unchecked. With an unchecked exception, however, the compiler doesnt 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: ArrayIndexOutOfBoundsException.
Errors are often irrecoverable conditions.

Q: Does the code in finally block get executed if there is an exception and a return statement in
a catch block? Or

Q: What is the purpose of the finally clause of a try-catch-finally statement?

The finally clause is used to provide the capability to execute code no matter whether or not an exception
is thrown or caught. 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(0) statement is executed
earlier or on system shut down earlier or the memory is used up earlier before the thread goes to finally
block.

y.rajashekher@gmail.com Page 52
try{
//some statements
}
catch{
//statements when exception is caught
}
finally{
//statements executed whether exception occurs or not
}

Does the order of placing catch statements matter in the catch block?

Yes, it does. The FileNoFoundException is inherited from the IOException. So FileNoFoundException is


caught before IOException. Exceptions subclasses have to be caught first before the General Exception

========================== ***************** =========================


Java Threads Interview Questions
Q: What are three ways in which a thread can enter the waiting state? Or

Q: What are different ways in which a thread can enter the waiting state?

A thread can enter the waiting state by the following ways:


1. Invoking its sleep() method,
2. By blocking on I/O
3. By unsuccessfully attempting to acquire an objects lock
4. By invoking an objects wait() method.
5. It can also enter the waiting state by invoking its (deprecated) suspend() method.

Q: What is the difference between yielding and sleeping?

When a task invokes its yield() method, it returns to the ready state, either from waiting, running or after
its creation. When a task invokes its sleep() method, it returns to the waiting state from a running state.

Q: How to create multithreaded program? Explain different ways of using thread? When a thread
is created and started, what is its initial state? Or

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

Q: What is mutual exclusion? How can you take care of mutual exclusion using Java threads?

y.rajashekher@gmail.com Page 53
Mutual exclusion is a phenomenon where no two processes can access critical regions of memory at the
same time. Using Java multithreading we can arrive at mutual exclusion. For mutual exclusion, you can
simply use the synchronized keyword and explicitly or implicitly provide an Object, any Object, to
synchronize on. The synchronized keyword can be applied to a class, to a method, or to a block of code.
There are several methods in Java used for communicating mutually exclusive threads such as wait( ),
notify( ), or notifyAll( ). For example, the notifyAll( ) method wakes up all threads that are in the wait list of
an object.

Q: What invokes a threads run() method?

After a thread is started, via its start() method of the Thread class, the JVM invokes the threads run()
method when the thread is initially executed.

Q: What is the purpose of the wait(), notify(), and notifyAll() methods?

The wait(), notify() and notifyAll() methods are used to provide an efficient way for thread inter-
communication.

Q: What is thread? What are the high-level thread states? Or

Q: What are the states associated in the thread?

A thread is an independent path of execution in a system. The high-level thread states are ready, running,
waiting and dead.

Q: What is deadlock?

When two threads are waiting for each other and cant proceed until the first thread obtains a lock on the
other thread or vice versa, the program is said to be in a deadlock.

Q: How does multithreading take place on a computer with a single CPU?

The operating systems task scheduler allocates execution time to multiple tasks. By quickly switching
between executing tasks, it creates the impression that tasks execute sequentially.

Q: What are synchronized methods and synchronized statements?

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

Q: Can Java object be locked down for exclusive use by a given thread? Or

Q: What happens when a thread cannot acquire a lock on an object?

Yes. You can lock an object by putting it in a synchronized block. The locked object is inaccessible to
any thread other than the one that explicitly claimed it. If a thread attempts to execute a synchronized
method or synchronized statement and is unable to acquire an objects lock, it enters the waiting state
until the lock becomes available.

Q: Whats the difference between the methods sleep() and wait()?

y.rajashekher@gmail.com Page 54
The sleep method is used when the thread has to be put aside for a fixed amount of time. Ex:
sleep(1000), puts the thread aside for exactly one second. The wait method is used to put the thread
aside for up to the specified time. It could wait for much lesser time if it receives a notify() or notifyAll()
call. Ex: wait(1000), causes a wait of up to one second. The method wait() is defined in the Object and the
method sleep() is defined in the class Thread.

Q: What is the difference between process and thread?

A thread is a separate path of execution in a program. A Process is a program in execution.

Q: What is daemon thread and which method is used to create the daemon thread?

Daemon threads are threads with low priority and runs in the back ground doing the garbage collection
operation for the java runtime system. The setDaemon() method is used to create a daemon thread.
These threads run without the intervention of the user. To determine if a thread is a daemon thread, use
the accessor method isDaemon()

When a standalone application is run then as long as any user threads are active the JVM cannot
terminate, otherwise the JVM terminates along with any daemon threads which might be active. Thus a
daemon thread is at the mercy of the runtime system. Daemon threads exist only to serve user threads.

Q: What do you understand by Synchronization? Or

Q: What is synchronization and why is it important? Or

Q: Describe synchronization in respect to multithreading? Or

Q: What is synchronization?

With respect to multithreading, Synchronization is a process of controlling the access of shared resources
by the multiple threads in such a manner that only one thread can access a particular resource at a time.
In non synchronized multithreaded application, it is possible for one thread to modify a shared object
while another thread is in the process of using or updating the objects value. Synchronization prevents
such type of data corruption which may otherwise lead to dirty reads and significant errors.
E.g. synchronizing a function:
public synchronized void Method1 () {
// method code.
}
E.g. synchronizing a block of code inside a function:
public Method2 (){
synchronized (this) {
// synchronized code here.
}
}

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

Q: Why would you use a synchronized block vs. synchronized method?

y.rajashekher@gmail.com Page 55
Synchronized blocks place locks for shorter periods than synchronized methods.

Q: What is an objects lock and which objects have locks?

Answer: An objects 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
objects lock. All objects and classes have locks. A classs lock is acquired on the classs Class object.

Q: Can a lock be acquired on a class?

Yes, a lock can be acquired on a class. This lock is acquired on the classs Class object.

Q: What state does a thread enter when it terminates its processing?

When a thread terminates its processing, it enters the dead state.

Q: How would you implement a thread pool?

public class ThreadPool implements ThreadPoolInt

This class is an generic implementation of a thread pool, which takes the following input

a) Size of the pool to be constructed

b) Name of the class which implements Runnable and constructs a thread pool with active threads that
are waiting for activation. Once the threads have finished processing they come back and wait once again
in the pool.

This thread pool engine can be locked i.e. if some internal operation is performed on the pool then it is
preferable that the thread engine be locked. Locking ensures that no new threads are issued by the
engine. However, the currently executing threads are allowed to continue till they come back to the
passivePool.

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

========================== ***************** =========================


Java Wrapper Classes Interview Questions

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

y.rajashekher@gmail.com Page 56
Following table lists the primitive types and the corresponding wrapper classes:

Primitive Wrapper
Boolean java.lang.Boolean
Byte java.lang.Byte
Char java.lang.Character
double java.lang.Double
Float java.lang.Float
Int java.lang.Integer
Long java.lang.Long
Short java.lang.Short
Void java.lang.Void

========================== ***************** =========================

Java Collections Interview Questions


Q: What is the Collections API?
A: The Collections API is a set of classes and interfaces that support operations on
collections of objects.

Q: What is the List interface?


A: The List interface provides support for ordered collections of objects.

Q: What is the Vector class?


A: The Vector class provides the capability to implement a growable array of objects.

Q: What is an Iterator interface?


A: The Iterator interface is used to step through the elements of a Collection .

Q: Which java.util classes and interfaces support event handling?


A: The EventObject class and the EventListener interface support event processing.

Q: What is the GregorianCalendar class?


A: The GregorianCalendar provides support for traditional Western calendars

Q: What is the Locale class?


A: The Locale class is used to tailor program output to the conventions of a particular
geographic, political, or cultural region .

Q: What is the SimpleTimeZone class?

y.rajashekher@gmail.com Page 57
A: The SimpleTimeZone class provides support for a Gregorian calendar .

Q: What is the Map interface?


A: The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with
values.

Q: What is the highest-level event class of the event-delegation model?


A: The java.util.EventObject class is the highest-level class in the event-delegation class
hierarchy.

Q: What is the Collection interface?


A: The Collection interface provides support for the implementation of a mathematical bag -
an unordered collection of objects that may contain duplicates.

Q: What is the Set interface?


A: The Set interface provides methods for accessing the elements of a finite mathematical
set. Sets do not allow duplicate elements.

Q: What is the typical use of Hashtable?


A: Whenever a program wants to store a key value pair, one can use Hashtable.

Q: I am trying to store an object using a key in a Hashtable. And some other object
already exists in that location, then what will happen? The existing object will
be overwritten? Or the new object will be stored elsewhere?
A: The existing object will be overwritten and thus it will be lost.

Q: What is the difference between the size and capacity of a Vector?


A: The size is the number of elements actually stored in the vector, while capacity is the
maximum number of elements it can store at a given instance of time.

Q: Can a vector contain heterogenous objects?


A: Yes a Vector can contain heterogenous objects. Because a Vector stores everything in
terms of Object.

Q: Can a ArrayList contain heterogenous objects?


A: Yes a ArrayList can contain heterogenous objects. Because a ArrayList stores everything
in terms of Object.

Q: What is an enumeration?
A: An enumeration is an interface containing methods for accessing the underlying data
structure from which the enumeration is obtained. It is a construct which collection
classes return when you request a collection of all the objects stored in the collection. It

y.rajashekher@gmail.com Page 58
allows sequential access to all the elements stored in the collection.

Q: Considering the basic properties of Vector and ArrayList, where will you use
Vector and where will you use ArrayList?
A: The basic difference between a Vector and an ArrayList is that, vector is synchronized
while ArrayList is not. Thus whenever there is a possibility of multiple threads accessing
the same instance, one should use Vector. While if not multiple threads are going to
access the same instance then use ArrayList. Non synchronized data structure will give
better performance than the synchronized one.

Q: Can a vector contain heterogenous objects?

Yes a Vector can contain heterogenous objects. Because a Vector stores everything in
terms of Object

Q: What is HashMap and Map?

Map is Interface and Hashmap is class that implements this interface.

Q: What is the significance of ListIterator? Or

Q: What is the difference b/w Iterator and ListIterator?

Iterator : Enables you to cycle through a collection in the forward direction only, for obtaining or
removing elements

ListIterator : It extends Iterator, allow bidirectional traversal of list and the modification of elements

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 doesnt allow nulls).
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 isnt.

Note on Some Important Terms


1)Synchronized means only one thread can modify a hash table at one point of time. Basically, it
means that any thread before performing an update on a hashtable will have to acquire a lock on the
object while others will wait for lock to be released.

2)Fail-safe is relevant from the context of iterators. If an iterator has been created on a collection
object and some other thread tries to modify the collection object structurally, a concurrent
modification exception will be thrown. It is possible for other threads though to invoke set method
since it doesnt modify the collection structurally. However, if prior to calling set, the collection has
been modified structurally, IllegalArgumentException will be thrown.

HashMap can be synchronized by Map m = Collections.synchronizeMap(hashMap);

y.rajashekher@gmail.com Page 59
Q: 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.

Q: Difference between Vector and ArrayList? What is the Vector class?

Vector is synchronized whereas ArrayList is not. The Vector class provides the capability to implement
a growable array of objects. ArrayList and Vector class both implement the List interface. Both classes
are implemented using dynamically resizable arrays, providing fast random access and fast traversal.
In vector the data is retrieved using the elementAt() method while in ArrayList, it is done using the get()
method. ArrayList has no default size while vector has a default size of 10. when you want programs to
run in multithreading environment then use concept of vector because it is synchronized. But ArrayList
is not synchronized so, avoid use of it in a multithreading environment.

Q: What is an Iterator interface? Is Iterator a Class or Interface? What is its use?

The Iterator is an interface, used to traverse through the elements of a Collection. It is not advisable to
modify the collection itself while traversing an Iterator.

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

Q: What is the List interface?

The List interface provides support for ordered collections of objects.

Q: How can we access elements of a collection?

We can access the elements of a collection using the following ways:


1.Every collection object has get(index) method to get the element of the object. This method will
return Object.
2.Collection provide Enumeration or Iterator object so that we can get the objects of a collection one
by one.

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

Q: Whats the difference between a queue and a stack?

Stack is a data structure that is based on last-in-first-out rule (LIFO), while queues are based on First-
in-first-out (FIFO) rule.

Q: What is the Map interface?

y.rajashekher@gmail.com Page 60
The Map interface is used associate keys with values.

Q: What is the Properties class?

The properties class is a subclass of Hashtable that can be read from or written to a stream. It also
provides the capability to specify a set of default values to be used.

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

Q: How can we use hashset in collection interface?

This class implements the set interface, backed by a hash table (actually a HashMap instance). It
makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the
order will remain constant over time. This class permits the Null element.

This class offers constant time performance for the basic operations (add, remove, contains and size),
assuming the hash function disperses the elements properly among the buckets.

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

Q: What is difference between array & arraylist?

An ArrayList is resizable, where as, an array is not. ArrayList is a part of the Collection Framework. We
can store any type of objects, and we can deal with only objects. It is growable. Array is collection of
similar data items. We can have array of primitives or objects. It is of fixed size. We can have multi

y.rajashekher@gmail.com Page 61
dimensional arrays.

Array: can store primitive ArrayList: Stores object only

Array: fix size ArrayList: resizable

Array: can have multi dimensional

Array: lang ArrayList: Collection framework

Q: Can you limit the initial capacity of vector in java?

Yes you can limit the initial capacity. We can construct an empty vector with specified initial capacity

public vector(int initialcapacity)

Q: What method should the key class of Hashmap override?

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

Q: What is the difference between Enumeration and Iterator?

The functionality of Enumeration interface is duplicated by the Iterator interface. Iterator has a
remove() method while Enumeration doesnt. Enumeration acts as Read-only interface, because it has
the methods only to traverse and fetch the objects, where as using Iterator we can manipulate the
objects also like adding and removing the objects.

So Enumeration is used whenever we want to make Collection objects as Read-only

Q: Explain Java Collections Framework?


Java Collections Framework provides a well designed set of interfaces and classes that
support operations on collections of objects.2) Explain Iterator Interface.
An Iterator is similar to the Enumeration interface.With the Iterator interface methods,
you can traverse a collection from start to end and safely remove elements from the
underlying Collection. The iterator() method generally used in query operations.
Basic methods:
iterator.remove();
iterator.hasNext();
iterator.next();

Q: Explain Enumeration 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.
Basic methods:
boolean hasMoreElements();
Object nextElement();

Q: What is the difference between Enumeration and Iterator interface?


The Enumeration interface allows you to iterate through all the elements of a collection.

y.rajashekher@gmail.com Page 62
Iterating through an Enumeration is similar to iterating through an Iterator. However,
there is no removal support with Enumeration.

Q: Explain Set Interface.


In mathematical concept, a set is just a group of unique items, in the sense that the
group contains no duplicates. The Set interface extends the Collection interface. Set does
not allow duplicates in the collection. In Set implementations null is valid entry, but
allowed only once.

Q: What are the two types of Set implementations available in the Collections
Framework?
HashSet and TreeSet are the two Set implementations available in the Collections
Framework.

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

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

Q: What is a List?
List is a ordered and non duplicated collection of objects. The List interface extends the
Collection interface.

Q: What are the two types of List implementations available in the Collections
Framework?
ArrayList and LinkedList are the two List implementations available in the Collections
Framework.

Q: What is the difference between ArrayList and LinkedList?


The ArrayList Class implements java.util.List interface and uses array for storage. An
array storages 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.

Q: What collection will you use to implement a queue?


LinkedList

Q: Explain Map Interface.


A map is a special kind of set with no duplicates.The key values are used to lookup, or
index the stored data. The Map interface is not an extension of Collection interface, it has
its own hierarchy. Map does not allow duplicates in the collection. In Map
implementations null is valid entry, but allowed only once.

y.rajashekher@gmail.com Page 63
Q: What are the two types of Map implementations available in the Collections
Framework?
HashMap and TreeMap are two types of Map implementations available in the Collections
Framework.

y.rajashekher@gmail.com Page 64
Q: What is the difference between HashMap and TreeMap?
The HashMap Class implements java.util.Map interface and uses hashing for storage.
Indirectly Map uses Set functionality so, it does not permit duplicates. The TreeMap Class
implements java.util.Map interface and uses tree for storage. It provides the ordered
map.

Q: Explain the functionality of Vector Class?


Once array size is set you cannot change size of the array. To deal with this kind of
situations in Java uses Vector, it grows and shrink its size automatically. Vector allows to
store only objects not primitives. To store primitives, convert primitives in to objects
using wrapper classes before adding them into Vector.The Vector reallocates and resizes
itself automatically.

Q: What does the following statement convey?


Vector vt = new Vector(3, 10);
vt is an instance of Vector class with an initial capacity of 3 and grows in increment of 10
in each relocation

Q: How do you store a primitive data type within a Vector or other collections
class?
You need to wrap the primitive data type into one of the wrapper classes found in the
java.lang package, like Integer, Float, or Double, as in:
Integer in = new Integer(5);

Q: What is the difference between Vector and ArrayList?


Vector and ArrayList are very similar. Both of them represent a growable array. The main
difference is that Vector is synchronized while ArrayList is not.

Q: What is the between Hashtable and HashMap?


Both provide key-value access to data. The key differences are :
a. Hashtable is synchronised but HasMap is not synchronised.
b. HashMap permits null values but Hashtable doent allow null values.
c. iterator in the HashMap is fail-safe while the enumerator for the Hashtable is not fail
safe.

Q: How do I make an array larger?


You cannot directly make an array larger. You must make a new (larger) array and copy
the original elements into it, usually with System.arraycopy(). If you find yourself
frequently doing this, the Vector class does this automatically for you, as long as your
arrays are not of primitive data types.

Q: Which is faster, synchronizing a HashMap or using a Hashtable for thread-


safe access?
Because a synchronized HashMap requires an extra method call, a Hashtable is faster for
synchronized access.

y.rajashekher@gmail.com Page 65
========================== ***************** =========================
Java Interview Questions
* Q1. How could Java classes direct program messages to the system console, but error
messages, say to a file?

A. The class System has a variable out that represents the standard output, and the variable err
that represents the standard error device. By default, they both point at the system console. This
how the standard output could be re-directed:

Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st);


System.setOut(st);

* Q2. What's the difference between an interface and an abstract class?

A. An abstract class may contain code in method bodies, which is not allowed in an interface. With
abstract classes, you have to inherit your class from it and Java does not allow multiple
inheritance. On the other hand, you can implement multiple interfaces in your class.

* Q3. Why would you use a synchronized block vs. synchronized method?

A. Synchronized blocks place locks for shorter periods than synchronized methods.

* Q4. Explain the usage of the keyword transient?

A. This keyword indicates that the value of this member variable does not have to be serialized
with the object. When the class will be de-serialized, this variable will be initialized with a default
value of its data type (i.e. zero for integers).

* Q5. How can you force garbage collection?

A. You can't force GC, but could request it by calling System.gc(). JVM does not guarantee that GC
will be started immediately.

* Q6. How do you know if an explicit object casting is needed?

A. If you assign a superclass object to a variable of a subclass's data type, you need to do explicit
casting. For example:

Object a; Customer b; b = (Customer) a;

When you assign a subclass to a variable having a supeclass type, the casting is performed
automatically.

* Q7. What's the difference between the methods sleep() and wait()

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

* Q8. Can you write a Java class that could be used both as an applet as well as an
application?

A. Yes. Add a main() method to the applet.

* Q9. What's the difference between constructors and other methods?

y.rajashekher@gmail.com Page 66
A. 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.

* Q10. Can you call one constructor from another if a class has multiple constructors

A. Yes. Use this() syntax.

* Q11. Explain the usage of Java packages.

A. This is a way to organize files when a project consists of multiple modules. It also helps resolve
naming conflicts when different packages have classes with the same names. Packages access
level also allows you to protect data from being used by the non-authorized classes.

* Q12. If a class is located in a package, what do you need to change in the OS


environment to be able to use it?

A. You need to add a directory or a jar file that contains the package directories to the CLASSPATH
environment variable. Let's say a class Employee belongs to a package com.xyz.hr; and is located
in the file c:\dev\com\xyz\hr\Employee.java. In this case, you'd need to add c:\dev to the variable
CLASSPATH. If this class contains the method main(), you could test it from a command prompt
window as follows:

c:\>java com.xyz.hr.Employee

* Q13. What's the difference between J2SDK 1.5 and J2SDK 5.0?

A.There's no difference, Sun Microsystems just re-branded this version.

* Q14. What would you use to compare two String variables - the operator == or the
method equals()?

A. I'd use the method equals() to compare the values of the Strings and the == to check if two
variables point at the same instance of a String object.

* Q15. Does it matter in what order catch statements for FileNotFoundException and
IOExceptipon are written?

A. Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses
have to be caught first.

* Q16. Can an inner class declared inside of a method access local variables of this
method?

A. It's possible if these variables are final.

* Q17. What can go wrong if you replace && with & in the following code:

String a=null; if (a!=null && a.length()>10) {...}

A. A single ampersand here would lead to a NullPointerException.

* Q18. What's the main difference between a Vector and an ArrayList

A. Java Vector class is internally synchronized and ArrayList is not.

* Q19. When should the method invokeLater()be used?

y.rajashekher@gmail.com Page 67
A. This method is used to ensure that Swing components are updated through the event-
dispatching thread.

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

A. Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write
super(); in the first line of the subclass's constructor.
** Q21. What's the difference between a queue and a stack?

A. Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule

** Q22. You can create an abstract class that contains only abstract methods. On the
other hand, you can create an interface that declares the same methods. So can you use
abstract classes instead of interfaces?

A. Sometimes. But your class may be a descendent of another class and in this case the interface
is your only option.

** Q23. What comes to mind when you hear about a young generation in Java?

A. Garbage collection.

** Q24. What comes to mind when someone mentions a shallow copy in Java?

A. Object cloning.

** Q25. If you're overriding the method equals() of an object, which other method you
might also consider?

A. hashCode()

** Q26. You are planning to do an indexed search in a list of objects. Which of the two
Java collections should you use:
ArrayList or LinkedList?

A. ArrayList

** Q27. How would you make a copy of an entire Java object with its state?

A. Have this class implement Cloneable interface and call its method clone().

** Q28. How can you minimize the need of garbage collection and make the memory use
more effective?

A. Use object pooling and weak object references.

** Q29. There are two classes: A and B. The class B need to inform a class A when some
important event has happened. What Java technique would you use to implement it?

A. If these classes are threads I'd consider notify() or notifyAll(). For regular classes you can use
the Observer interface.

** Q30. What access level do you need to specify in the class declaration to ensure that
only classes from the same directory can access it?

A. You do not need to specify any access level, and Java will use a default package access level.

y.rajashekher@gmail.com Page 68
========================== ***************** =========================
JAVA INTERVIEW QUESTIONS

y.rajashekher@gmail.com Page 69
Question : When you declare a method as abstract method ?

Answer : When i want child class to implement the behavior of the method.

Question : Can I call a abstract method from a non abstract method ?

Answer : Yes, We can call a abstract method from a Non abstract method in a Java
abstract class

Question : What is the difference between an Abstract class and Interface in


Java ? or can you explain when you use Abstract classes ?

Answer : Abstract classes let you define some behaviors; they force your subclasses
to provide others. These abstract classes will provide the basic funcationality
of your applicatoin, child class which inherited this class will provide the
funtionality of the abstract methods in abstract class. When base class calls
this method, Java calls the method defined by the child class.

An Interface can only declare constants and instance methods, but


cannot implement default behavior.
Interfaces provide a form of multiple inheritance. 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.
A Class may implement several interfaces. But in case of abstract
class, a class may extend only one abstract class.
Interfaces are slow as it requires extra indirection to find
corresponding method in the actual class. Abstract classes are fast.

Neither
Abstra
ct
classes
or
Interfa
ce can
be
instanti
ated.

Question : What is user-defined exception in java ?

Answer : User-defined expections are the exceptions defined by the application


developer
y.rajashekher@gmail.com Pagewhich
70 are errors related to specific application. Application
Developer can define the user defined exception by inherite the Exception
class as shown below. Using this class we can throw new exceptions.
========================== ***************** =========================
Java Interview Questions

Question: How could Java classes direct program messages to the system console, but error
messages, say to a file?

Answer: The class System has a variable out that represents the standard output, and the variable
err that represents the standard error device. By default, they both point at the system console.
This how the standard output could be re-directed:

Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st);


System.setOut(st);

Question: What's the difference between an interface and an abstract class?

Answer: An abstract class may contain code in method bodies, which is not allowed in an
interface. With abstract classes, you have to inherit your class from it and Java does not allow
multiple inheritance. On the other hand, you can implement multiple interfaces in your class.

Question: Why would you use a synchronized block vs. synchronized method?

Answer: Synchronized blocks place locks for shorter periods than synchronized methods.

Question: Explain the usage of the keyword transient?

Answer: This keyword indicates that the value of this member variable does not have to be
serialized with the object. When the class will be de-serialized, this variable will be initialized
with a default value of its data type (i.e. zero for integers).

Question: How can you force garbage collection?

Answer: You can't force GC, but could request it by calling System.gc(). JVM does not
guarantee that GC will be started immediately.

Question: How do you know if an explicit object casting is needed?

Answer: If you assign a superclass object to a variable of a subclass's data type, you need to do
explicit casting. For example:

Object a; Customer b; b = (Customer) a;

When you assign a subclass to a variable having a supeclass type, the casting is performed
automatically.

Question: What's the difference between the methods sleep() and wait()

y.rajashekher@gmail.com Page 71
Answer: 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.

Question: Can you write a Java class that could be used both as an applet as well as an
application?

Answer: Yes. Add a main() method to the applet.

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.

Question: Can you call one constructor from another if a class has multiple constructors

Answer: Yes. Use this() syntax.

Question: Explain the usage of Java packages.

Answer: This is a way to organize files when a project consists of multiple modules. It also helps
resolve naming conflicts when different packages have classes with the same names. Packages
access level also allows you to protect data from being used by the non-authorized classes.

Question: If a class is located in a package, what do you need to change in the OS


environment to be able to use it?

Answer: You need to add a directory or a jar file that contains the package directories to the
CLASSPATH environment variable. Let's say a class Employee belongs to a package
com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.java. In this case, you'd need
to add c:\dev to the variable CLASSPATH. If this class contains the method main(), you could
test it from a command prompt window as follows:

c:\>java com.xyz.hr.Employee

Question: What's the difference between J2SDK 1.5 and J2SDK 5.0?

Answer: There's no difference, Sun Microsystems just re-branded this version.

Question: What would you use to compare two String variables - the operator == or the method
equals()?

Answer: I'd use the method equals() to compare the values of the Strings and the == to check if
two variables point at the same instance of a String object.

y.rajashekher@gmail.com Page 72
Question: Does it matter in what order catch statements for FileNotFoundException and
IOExceptipon are written?

Answer: Yes, it does. The FileNoFoundException is inherited from the IOException.


Exception's subclasses have to be caught first.

Question: Can an inner class declared inside of a method access local variables of this
method?

Answer: It's possible if these variables are final.

Question: What can go wrong if you replace && with & in the following code: String
a=null; if (a!=null && a.length()>10) {...}

Answer: A single ampersand here would lead to a NullPointerException.

Question: What's the main difference between a Vector and an ArrayList

Answer: Java Vector class is internally synchronized and ArrayList is not.

Question: When should the method invokeLater()be used?

Answer: This method is used to ensure that Swing components are updated through the event-
dispatching thread.

Question: How can a subclass call a method or a constructor defined in a superclass?

Answer: Use the following syntax: super.myMethod(); To call a constructor of the superclass,
just write super(); in the first line of the subclass's constructor.

For senior-level developers:

Question: What's the difference between a queue and a stack?

Answer: Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule

Question: You can create an abstract class that contains only abstract methods. On the
other hand, you can create an interface that declares the same methods. So can you use
abstract classes instead of interfaces?

Answer: Sometimes. But your class may be a descendent of another class and in this case the
interface is your only option.

Question: What comes to mind when you hear about a young generation in Java?

Answer: Garbage collection.

y.rajashekher@gmail.com Page 73
Question: What comes to mind when someone mentions a shallow copy in Java?

Answer: Object cloning.

Question: If you're overriding the method equals() of an object, which other method you
might also consider?

Answer: hashCode()

Question: You are planning to do an indexed search in a list of objects. Which of the two
Java collections should you use: ArrayList or LinkedList?

Answer: ArrayList

Question: How would you make a copy of an entire Java object with its state?

Answer: Have this class implement Cloneable interface and call its method clone().

Question: How can you minimize the need of garbage collection and make the memory use
more effective?

Answer: Use object pooling and weak object references.

Question: There are two classes: A and B. The class B need to inform a class A when some
important event has happened. What Java technique would you use to implement it?

Answer: If these classes are threads I'd consider notify() or notifyAll(). For regular classes you
can use the Observer interface.

Question: What access level do you need to specify in the class declaration to ensure that
only classes from the same directory can access it?

Answer: You do not need to specify any access level, and Java will use a default package access
level .

Question: When you declare a method as abstract method ?

Answer: When i want child class to implement the behavior of the method.

Question: Can I call a abstract method from a non abstract method ?

Answer: Yes, We can call a abstract method from a Non abstract method in a Java abstract class

y.rajashekher@gmail.com Page 74
Question: What is the difference between an Abstract class and Interface in Java ? or can you
explain when you use Abstract classes ?

Answer: Abstract classes let you define some behaviors; they force your subclasses to provide
others. These abstract classes will provide the basic funcationality of your applicatoin, child class
which inherited this class will provide the funtionality of the abstract methods in abstract class.
When base class calls this method, Java calls the method defined by the child class.

An Interface can only declare constants and instance methods, but cannot implement
default behavior.
Interfaces provide a form of multiple inheritance. 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.
A Class may implement several interfaces. But in case of abstract class, a class may
extend only one abstract class.
Interfaces are slow as it requires extra indirection to find corresponding method in the
actual class. Abstract classes are fast.

Question: What is user-defined exception in java ?

Answer: User-defined expections are the exceptions defined by the application developer which
are errors related to specific application. Application Developer can define the user defined
exception by inherite the Exception class as shown below. Using this class we can throw new
exceptions.

Java Example : public class noFundException extends Exception { } Throw an exception using
a throw statement: public class Fund { ... public Object getFunds() throws noFundException { if
(Empty()) throw new noFundException(); ... } } User-defined exceptions should usually be
checked

Question: What are different types of inner classes ?

Answer: Inner classes nest within other classes. A normal class is a direct member of a package.
Inner classes, which became available with Java 1.1, are four types

Static member classes


Member classes
Local classes
Anonymous classes

Static member classes - 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.

Member Classes - a member class is also defined as a member of a class. Unlike the static
variety, the member class is instance specific and has access to any and all methods and

y.rajashekher@gmail.com Page 75
members, even the parent's this reference.

Local Classes - Local Classes declared within a block of code and these classes are visible only
within the block.

Anonymous Classes - These type of classes does not have any name and its like a local class

Java Anonymous Class Example public class SomeGUI extends JFrame { ... button member
declarations ... protected void buildGUI() { button1 = new JButton(); button2 = new JButton(); ...
button1.addActionListener( new java.awt.event.ActionListener() <------ Anonymous Class
{ public void actionPerformed(java.awt.event.ActionEvent e) { // do something } } );

Question: What are the uses of Serialization?

Answer: In some types of applications you have to write the code to serialize objects, but in
many cases serialization is performed behind the scenes by various server-side containers.

These are some of the typical uses of serialization:

To persist data for future use.


To send data to a remote computer using such client/server Java technologies as RMI or
socket programming.
To "flatten" an object into array of bytes in memory.
To exchange data between applets and servlets.
To store user session in Web applications.
To activate/passivate enterprise java beans.
To send objects between the servers in a cluster.

Question: what is a collection ?

Answer: Collection is a group of objects. java.util package provides important types of


collections. There are two fundamental types of collections they are Collection and Map.
Collection types hold a group of objects, Eg. Lists and Sets where as Map types hold group of
objects as key, value pairs Eg. HashMap and Hashtable.

Question: For concatenation of strings, which method is good, StringBuffer or String ?

Answer: StringBuffer is faster than String for concatenation.

Question: What is Runnable interface ? Are there any other ways to make a java program as
multithred java program?

Answer: There are two ways to create new kinds of threads:

- Define a new class that extends the Thread class


- Define a new class that implements the Runnable interface, and pass an object of that class to a

y.rajashekher@gmail.com Page 76
Thread's constructor.
- An advantage of the second approach is that the new class can be a subclass of any class, not
just of the Thread class.

Here is a very simple example just to illustrate how to use the second approach to creating
threads: class myThread implements Runnable { public void run() { System.out.println("I'm
running!"); } } public class tstRunnable { public static void main(String[] args) { myThread my1
= new myThread(); myThread my2 = new myThread(); new Thread(my1).start(); new
Thread(my2).start(); }

Question: How can i tell what state a thread is in ?

Answer: Prior to Java 5, isAlive() was commonly used to test a threads state. If isAlive()
returned false the thread was either new or terminated but there was simply no way to
differentiate between the two.

Starting with the release of Tiger (Java 5) you can now get what state a thread is in by using the
getState() method which returns an Enum of Thread.States. A thread can only be in one of the
following states at a given point in time.

NEW A Fresh thread that has not yet started to execute.


RUNNABLE A thread that is executing in the Java virtual machine.
BLOCKED A thread that is blocked waiting for a monitor lock.
WAITING A thread that is wating to be notified by another thread.
A thread that is wating to be notified by another thread for a specific amount
TIMED_WAITING
of time
TERMINATED A thread whos run method has ended.
The folowing code prints out all thread states. public class ThreadStates{ public static void
main(String[] args){ Thread t = new Thread(); Thread.State e = t.getState(); Thread.State[] ts =
e.values(); for(int i = 0; i < ts.length; i++){ System.out.println(ts[i]); } } }

Question: What methods java providing for Thread communications ?

Answer: Java provides three methods that threads can use to communicate with each other: wait,
notify, and notifyAll. These methods are defined for all Objects (not just Threads). The idea is
that a method called by a thread may need to wait for some condition to be satisfied by another
thread; in that case, it can call the wait method, which causes its thread to wait until another
thread calls notify or notifyAll.

Question: What is the difference between notify and notify All methods ?

Answer: A call to notify causes at most one thread waiting on the same object to be notified
(i.e., the object that calls notify must be the same as the object that called wait). A call to
notifyAll causes all threads waiting on the same object to be notified. If more than one thread is

y.rajashekher@gmail.com Page 77
waiting on that object, there is no way to control which of them is notified by a call to notify (so
it is often better to use notifyAll than notify).

Question: What is synchronized keyword? In what situations you will Use it?

Answer: Synchronization is the act of serializing access to critical sections of code. We will use
this keyword when we expect multiple threads to access/modify the same data. To understand
synchronization we need to look into thread execution manner.

Threads may execute in a manner where their paths of execution are completely independent of
each other. Neither thread depends upon the other for assistance. For example, one thread might
execute a print job, while a second thread repaints a window. And then there are threads that
require synchronization, the act of serializing access to critical sections of code, at various
moments during their executions. For example, say that two threads need to send data packets
over a single network connection. Each thread must be able to send its entire data packet before
the other thread starts sending its data packet; otherwise, the data is scrambled. This scenario
requires each thread to synchronize its access to the code that does the actual data-packet
sending.

If you feel a method is very critical for business that needs to be executed by only one thread at a
time (to prevent data loss or corruption), then we need to use synchronized keyword.

EXAMPLE

Some real-world tasks are better modeled by a program that uses threads than by a normal,
sequential program. For example, consider a bank whose accounts can be accessed and updated
by any of a number of automatic teller machines (ATMs). Each ATM could be a separate thread,
responding to deposit and withdrawal requests from different users simultaneously. Of course, it
would be important to make sure that two users did not access the same account simultaneously.
This is done in Java using synchronization, which can be applied to individual methods, or to
sequences of statements.

One or more methods of a class can be declared to be synchronized. When a thread calls an
object's synchronized method, the whole object is locked. This means that if another thread tries
to call any synchronized method of the same object, the call will block until the lock is released
(which happens when the original call finishes). In general, if the value of a field of an object can
be changed, then all methods that read or write that field should be synchronized to prevent two
threads from trying to write the field at the same time, and to prevent one thread from reading the
field while another thread is in the process of writing it.

Here is an example of a BankAccount class that uses synchronized methods to ensure that
deposits and withdrawals cannot be performed simultaneously, and to ensure that the account
balance cannot be read while either a deposit or a withdrawal is in progress. (To keep the
example simple, no check is done to ensure that a withdrawal does not lead to a negative
balance.)

y.rajashekher@gmail.com Page 78
public class BankAccount { private double balance; // constructor: set balance to given amount
public BankAccount( double initialDeposit ) { balance = initialDeposit; } public synchronized
double Balance( ) { return balance; } public synchronized void Deposit( double deposit )
{ balance += deposit; } public synchronized void Withdraw( double withdrawal ) { balance -=
withdrawal; } }

Note: that the BankAccount's constructor is not declared to be synchronized. That is because it
can only be executed when the object is being created, and no other method can be called until
that creation is finished.

There are cases where we need to synchronize a group of statements, we can do that using
synchrozed statement.

Java Code Example synchronized ( B ) { if ( D > B.Balance() ) { ReportInsuffucientFunds(); }


else { B.Withdraw( D ); } }

Question: What is serialization ?

Answer: Serialization is the process of writing complete state of java object into output stream,
that stream can be file or byte array or stream associated with TCP/IP socket.

Question: What does the Serializable interface do ?

Answer: Serializable is a tagging interface; it prescribes no methods. It serves to assign the


Serializable data type to the tagged class and to identify the class as one which the developer has
designed for persistence. ObjectOutputStream serializes only those objects which implement this
interface.

Question: How do I serialize an object to a file ?

Answer: To serialize an object into a stream perform the following actions:

- Open one of the output streams, for exaample FileOutputStream


- Chain it with the ObjectOutputStream - Call the method writeObject() providingg the instance
of a Serializable object as an argument.
- Close the streams

Java Code --------- try{ fOut= new FileOutputStream("c:\\emp.ser"); out = new


ObjectOutputStream(fOut); out.writeObject(employee); //serializing System.out.println("An
employee is serialized into c:\\emp.ser"); } catch(IOException e){ e.printStackTrace(); }

Question: How do I deserilaize an Object?

Answer: To deserialize an object, perform the following steps:

y.rajashekher@gmail.com Page 79
- Open an input stream
- Chain it with the ObjectInputStream - Call the method readObject() and cast tthe returned
object to the class that is being deserialized.
- Close the streams

Java Code try{ fIn= new FileInputStream("c:\\emp.ser"); in = new ObjectInputStream(fIn); //de-


serializing employee Employee emp = (Employee) in.readObject();
System.out.println("Deserialized " + emp.fName + " " + emp.lName + " from emp.ser "); }
catch(IOException e){ e.printStackTrace(); }catch(ClassNotFoundException e)
{ e.printStackTrace(); }

Question: What is Externalizable Interface ?

Answer : Externalizable interface is a subclass of Serializable. Java provides Externalizable


interface that gives you more control over what is being serialized and it can produce smaller
object footprint. ( You can serialize whatever field values you want to serialize)

This interface defines 2 methods: readExternal() and writeExternal() and you have to implement
these methods in the class that will be serialized. In these methods you'll have to write code that
reads/writes only the values of the attributes you are interested in. Programs that perform
serialization and deserialization have to write and read these attributes in the same sequence.

Question: Explain garbage collection ?

Answer: Garbage collection is an important part of Java's security strategy. Garbage collection
is also called automatic memory management as JVM automatically removes the unused
variables/objects from the memory. The name "garbage collection" implies that objects that are
no longer needed by the program are "garbage" and can be thrown away. A more accurate and
up-to-date metaphor might be "memory recycling." When an object is no longer referenced by
the program, the heap space it occupies must be recycled so that the space is available for
subsequent new objects. The garbage collector must somehow determine which objects are no
longer referenced by the program and make available the heap space occupied by such
unreferenced objects. In the process of freeing unreferenced objects, the garbage collector must
run any finalizers of objects being freed

Question : How you can force the garbage collection ?

Answer : Garbage collection automatic process and can't be forced. We can call garbage
collector in Java by 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.

Question : What are the field/method access levels (specifiers) and class access levels ?

Answer: Each field and method has an access level:

private: accessible only in this class

y.rajashekher@gmail.com Page 80
(package): accessible only in this package
protected: accessible only in this package and in all subclasses of this class
public: accessible everywhere this class is available

Similarly, each class has one of two possible access levels:

(package): class objects can only be declared and manipulated by code in this package

public: class objects can be declared and manipulated by code in any package

Question: What is an Iterator interface?

Answer: The Iterator interface is used to step through the elements of a Collection.

Question: What is the difference between the >> and >>> operators?

Answer: The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that
have been shifted out.

Question: Which method of the Component class is used to set the position and size of a
component?

Answer: setBounds()

Question: How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8
characters?

Answer: Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set
uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and
18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.

Question: What is the difference between yielding and sleeping?

Answer: When a task invokes its yield() method, it returns to the ready state. When a task
invokes its sleep() method, it returns to the waiting state.

Question: Which java.util classes and interfaces support event handling?

Answer: The EventObject class and the EventListener interface support event processing.

Question: Is sizeof a keyword?

Answer: The sizeof operator is not a keyword.

Question: What are wrapped classes?

y.rajashekher@gmail.com Page 81
Answer: Wrapped classes are classes that allow primitive types to be accessed as objects.

Question: Does garbage collection guarantee that a program will not run out of memory?

Answer: Garbage collection does not guarantee that a program will not run out of memory. It is
possible for programs to use up memory resources faster than they are garbage collected. It is
also possible for programs to create objects that are not subject to garbage collection

Question: What restrictions are placed on the location of a package statement within a
source code file?

Answer: A package statement must appear as the first line in a source code file (excluding blank
lines and comments).

Question: Can an object's finalize() method be invoked while it is reachable?

Answer: An object's finalize() method cannot be invoked by the garbage collector while the
object is still reachable. However, an object's finalize() method may be invoked by other objects.

Question: What is the immediate superclass of the Applet class?

Answer: Panel

Question: What is the difference between preemptive scheduling and time slicing?

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

Question: Name three Component subclasses that support painting.

Answer: The Canvas, Frame, Panel, and Applet classes support painting.

Question: What value does readLine() return when it has reached the end of a file?

Answer: The readLine() method returns null when it has reached the end of a file.

Question: What is a native method?

Answer: A native method is a method that is implemented in a language other than Java.

Question: Can a for statement loop indefinitely?

Answer: Yes, a for statement can loop indefinitely. For example, consider the following: for(;;) ;

y.rajashekher@gmail.com Page 82
Question: What are order of precedence and associativity, and how are they used?

Answer: Order of precedence determines the order in which operators are evaluated in
expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-
left

Question: When a thread blocks on I/O, what state does it enter?

Answer: A thread enters the waiting state when it blocks on I/O.

Question: To what value is a variable of the String type automatically initialized?

Answer: The default value of an String type is null.

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.

Question: What is the difference between a MenuItem and a CheckboxMenuItem?

Answer: The CheckboxMenuItem class extends the MenuItem class to support a menu item that
may be checked or unchecked.

Question: What is a task's priority and how is it used in scheduling?

Answer: A task's priority is an integer value that identifies the relative order in which it should
be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks
before lower priority tasks.

Question: What class is the top of the AWT event hierarchy?

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

Question: When a thread is created and started, what is its initial state?

Answer: A thread is in the ready state after it has been created and started.

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.

Question: What is the range of the short type?

y.rajashekher@gmail.com Page 83
Answer: The range of the short type is -(2^15) to 2^15 - 1.

Question: What is the range of the char type?

Answer: The range of the char type is 0 to 2^16 - 1.

Question: In which package are most of the AWT events that support the event-
delegation model defined?

Answer: Most of the AWT-related events of the event-delegation model are defined in the
java.awt.event package. The AWTEvent class is defined in the java.awt package.

Question: What is the immediate superclass of Menu?

Answer: MenuItem

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.

========================== ***************** =========================


Few Questions by Raj
Q: What is the command used for compiling a java program?
A: javac
Syntax: javac Filename.java Ex: javac Example.java

Q: What is the command used to run a java program?


A: java
Syntax: java Classname Ex: java Example
(javac takes the file name to compile the program, but java takes the class name to run the
program, remember the file name and class name can be different)

Q: What is the command to compile the program to generate the classes in package structure?
A: javac d Filename.java
( this creates the class in specified package structure, that is if we mentioned package name as
com.test in source file, the class file is generated in the folder com/test)

Q: What is the Library?


A: Library is nothing but a collection of classes and interfaces, in java it is called as the API.
To use the services provided by the library (API) we have to call the service from our
program.

Q: What is Framework?

y.rajashekher@gmail.com Page 84
A: What is also a collection of API which provides services for our program In Framework the
framework API will call the methods in our program

Q: What is the difference between Library and Framework?


A: In Library we have to call the methods from our program, whereas in Framework it will call
the methods of our program we are not going to call any methods.
For example: For and Applet the browser will call the doInit() method to provide the services
where as to use the Date class methods we have to call the methods from our program.

Q: What is a Desktop Application? Web Application? Enterprise Application? And what is the
difference between them?
A: Desktop Application: an application which runs only on one PC is known as Desktop
application also known as Standalone Application. Ex: Calculator
Web Application: An application which runs on the web is known as the web application.
Web application will consists of html, servlets, JSPs and supported classes. It should not
have EJBs
Enterprise Application: An application which is having large set of users and complex
business will be developed using Enterprise Java Beans. This application is called as the
Enterprise Application. It can be accessed throw web. It can consist of any of the EJBs,
Servlets, JSPs, html and other supporting classes.

========================== ***************** =========================

JDBC Interview Questions


1.What is the JDBC?
Java Database Connectivity (JDBC) is a standard Java API to interact with relational databases form
Java. JDBC has set of classes and interfaces which can use from Java application and talk to database
without learning RDBMS details and using Database Specific JDBC Drivers.

2.What are the new features added to JDBC 4.0?


The major features added in JDBC 4.0 include :

Auto-loading of JDBC driver class


Connection management enhancements
Support for RowId SQL type
DataSet implementation of SQL using Annotations
SQL exception handling enhancements
SQL XML support

3.Explain Basic Steps in writing a Java program using JDBC?


JDBC makes the interaction with RDBMS simple and intuitive. When a Java application needs to access
database :

Load the RDBMS specific JDBC driver because this driver actually communicates with the
database (Incase of JDBC 4.0 this is automatically loaded).

y.rajashekher@gmail.com Page 85
Open the connection to database which is then used to send SQL statements and get results
back.
Create JDBC Statement object. This object contains SQL query.
Execute statement which returns resultset(s). ResultSet contains the tuples of database table
as a result of SQL query.
Process the result set.
Close the connection.

4.Exaplain the JDBC Architecture.


The JDBC Architecture consists of two layers:

The JDBC API, which provides the application-to-JDBC Manager connection.


The JDBC Driver API, which supports the JDBC Manager-to-Driver Connection.

The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity
to heterogeneous databases. The JDBC driver manager ensures that the correct driver is used to access
each data source. The driver manager is capable of supporting multiple concurrent drivers connected
to multiple heterogeneous databases. The location of the driver manager with respect to the JDBC
drivers and the Java application is shown in Figure 1.

Figure 1: JDBC Architecture

5.What are the main components of JDBC ?

y.rajashekher@gmail.com Page 86
The life cycle of a servlet consists of the following phases:

DriverManager: Manages a list of database drivers. Matches connection requests from the java
application with the proper database driver using communication subprotocol. The first driver
that recognizes a certain subprotocol under JDBC will be used to establish a database
Connection.
Driver: The database communications link, handling all communication with the database.
Normally, once the driver is loaded, the developer need not call it explicitly.
Connection : Interface with all methods for contacting a database.The connection object
represents communication context, i.e., all communication with database is through
connection object only.
Statement : Encapsulates an SQL statement which is passed to the database to be parsed,
compiled, planned and executed.
ResultSet: The ResultSet represents set of rows retrieved due to query execution.

6.How the JDBC application works?


A JDBC application can be logically divided into two layers:
1. Driver layer
2. Application layer

Driver layer consists of DriverManager class and the available JDBC drivers.
The application begins with requesting the DriverManager for the connection.
An appropriate driver is choosen and is used for establishing the connection. This connection is
given to the application which falls under the application layer.
The application uses this connection to create Statement kind of objects, through which SQL
commands are sent to backend and obtain the results.

Figure 2: JDBC Application

7.How do I load a database driver with JDBC


4.0 / Java 6?
Provided the JAR file containing the driver is properly configured, just place the JAR file in the
classpath. Java developers NO longer need to explicitly load JDBC drivers using code like
Class.forName() to register a JDBC driver.The DriverManager class takes care of this by automatically
locating a suitable driver when the DriverManager.getConnection() method is called. This feature is
backward-compatible, so no changes are needed to the existing JDBC code.

8.What is JDBC Driver interface?

y.rajashekher@gmail.com Page 87
The JDBC Driver interface provides vendor-specific implementations of the abstract classes provided by
the JDBC API. Each vendor driver must provide implementations of the
java.sql.Connection,Statement,PreparedStatement, CallableStatement, ResultSet and
Driver.

9.What does the connection object represents?


The connection object represents communication context, i.e., all communication with database is
through connection object only.

10.What is Statement ?
Statement acts like a vehicle through which SQL commands can be sent. Through the connection
object we create statement kind of objects.
Through the connection object we create statement kind of objects.
Statement stmt = conn.createStatement();

This method returns object which implements statement interface.

11.What is PreparedStatement?
A prepared statement is an SQL statement that is precompiled by the database. Through
precompilation, prepared statements improve the performance of SQL commands that are executed
multiple times (given that the database supports prepared statements). Once compiled, prepared
statements can be customized prior to each execution by altering predefined SQL parameters.
PreparedStatement pstmt = conn.prepareStatement("UPDATE
EMPLOYEES SET SALARY = ? WHERE ID = ?");
pstmt.setBigDecimal(1, 153833.00);
pstmt.setInt(2, 110592);

Here: conn is an instance of the Connection class and "?" represents parameters.These parameters
must be specified before execution.

12.What is the difference between a Statement and a PreparedStatement?


Statement PreparedStatement
A PreparedStatement is a precompiled
A standard Statement is used to create a Java statement. This means that when the
representation of a literal SQL statement and PreparedStatement is executed, the RDBMS can
execute it on the database. just run the PreparedStatement SQL statement
without having to compile it first.
Statement has to verify its metadata against the While a prepared statement has to verify its
database every time. metadata against the database only once.
If you want to execute a single SQL statement
multiple number of times, then go for
If you want to execute the SQL statement once
PREPAREDSTATEMENT. PreparedStatement
go for STATEMENT
objects can be reused with passing different
values to the queries

y.rajashekher@gmail.com Page 88
13.What are callable statements ?
Callable statements are used from JDBC application to invoke stored procedures and functions.

14.How to call a stored procedure from JDBC ?


PL/SQL stored procedures are called from within JDBC programs by means of the prepareCall() method
of the Connection object created. A call to this method takes variable bind parameters as input
parameters as well as output variables and creates an object instance of the CallableStatement class.
The following line of code illustrates this:
CallableStatement stproc_stmt =
conn.prepareCall("{call procname(?,?,?)}");

Here conn is an instance of the Connection class.

15.What are types of JDBC drivers?


There are four types of drivers defined by JDBC as follows:

Type 1: JDBC/ODBCThese require an ODBC (Open Database Connectivity) driver for the
database to be installed. This type of driver works by translating the submitted queries into
equivalent ODBC queries and forwards them via native API calls directly to the ODBC driver. It
provides no host redirection capability.
Type2: Native API (partly-Java driver)This type of driver uses a vendor-specific driver or
database API to interact with the database. An example of such an API is Oracle OCI (Oracle
Call Interface). It also provides no host redirection.
Type 3: Open Protocol-NetThis is not vendor specific and works by forwarding database
requests to a remote database source using a net server component. How the net server
component accesses the database is transparent to the client. The client driver communicates
with the net server using a database-independent protocol and the net server translates this
protocol into database calls. This type of driver can access any database.
Type 4: Proprietary Protocol-Net(pure Java driver)This has a same configuration as a type 3
driver but uses a wire protocol specific to a particular vendor and hence can access only that
vendor's database. Again this is all transparent to the client.

Note: Type 4 JDBC driver is most preferred kind of approach in JDBC.

16.Which type of JDBC driver is the fastest one?


JDBC Net pure Java driver(Type IV) is the fastest driver because it converts the JDBC calls into vendor
specific protocol calls and it directly interacts with the database.

17.Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection?
No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge.

18.Which is the right type of driver to use and when?

Type I driver is handy for prototyping


Type III driver adds security, caching, and connection control
Type III and Type IV drivers need no pre-installation

Note: Preferred by 9 out of 10 Java developers: Type IV. Click here to learn more about JDBC drivers.

y.rajashekher@gmail.com Page 89
19.What are the standard isolation levels defined by JDBC?
The values are defined in the class java.sql.Connection and are:

TRANSACTION_NONE
TRANSACTION_READ_COMMITTED
TRANSACTION_READ_UNCOMMITTED
TRANSACTION_REPEATABLE_READ
TRANSACTION_SERIALIZABLE

Any given database may not support all of these levels.

20.What is resultset ?
The ResultSet represents set of rows retrieved due to query execution.
ResultSet rs = stmt.executeQuery(sqlQuery);

21.What are the types of resultsets?


The values are defined in the class java.sql.Connection and are:

TYPE_FORWARD_ONLY specifies that a resultset is not scrollable, that is, rows within it can be
advanced only in the forward direction.
TYPE_SCROLL_INSENSITIVE specifies that a resultset is scrollable in either direction but is
insensitive to changes committed by other transactions or other statements in the same
transaction.
TYPE_SCROLL_SENSITIVE specifies that a resultset is scrollable in either direction and is
affected by changes committed by other transactions or statements within the same
transaction.

Note: A TYPE_FORWARD_ONLY resultset is always insensitive.

22.Whats the difference between TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE?


TYPE_SCROLL_INSENSITIVE TYPE_SCROLL_SENSITIVE
An insensitive resultset is like the snapshot of A sensitive resultset does NOT represent a
the data in the database when query was snapshot of data, rather it contains points to
executed. those rows which satisfy the query condition.
After we get the resultset the changes made to After we obtain the resultset if the data is
data are not visible through the resultset, and modified then such modifications are visible
hence they are known as insensitive. through resultset.
Since a trip is made for every get operation,
Performance not effected with insensitive.
the performance drastically get affected.

22.What is rowset?
A RowSet is an object that encapsulates a set of rows from either Java Database Connectivity (JDBC)
result sets or tabular data sources like a file or spreadsheet. RowSets support component-based
development models like JavaBeans, with a standard set of properties and an event notification
mechanism.

24.What are the different types of RowSet ?

y.rajashekher@gmail.com Page 90
There are two types of RowSet are there. They are:

Connected - A connected RowSet object connects to the database once and remains connected
until the application terminates.
Disconnected - A disconnected RowSet object connects to the database, executes a query to
retrieve the data from the database and then closes the connection. A program may change
the data in a disconnected RowSet while it is disconnected. Modified data can be updated in
the database after a disconnected RowSet reestablishes the connection with the database.

25.What is the need of BatchUpdates?


The BatchUpdates feature allows us to group SQL statements together and send to database server in
one single trip.

26.What is a DataSource?
A DataSource object is the representation of a data source in the Java programming language. In basic
terms,

A DataSource is a facility for storing data.


DataSource can be referenced by JNDI.
Data Source may point to RDBMS, file System , any DBMS etc..

27.What are the advantages of DataSource?


The few advantages of data source are :

An application does not need to hardcode driver information, as it does with the
DriverManager.
The DataDource implementations can easily change the properties of data sources. For
example: There is no need to modify the application code when making changes to the
database details.
The DataSource facility allows developers to implement a DataSource class to take advantage
of features like connection pooling and distributed transactions.

28.What is connection pooling? what is the main advantage of using connection pooling?
A connection pool is a mechanism to reuse connections created. Connection pooling can increase
performance dramatically by reusing connections rather than creating a new physical connection each
time a connection is requested..

1 Q What is JDBC?
A JDBC technology is an API (included in both J2SE and J2EE releases) that provides cross-
DBMS connectivity to a wide range of SQL databases and access to other tabular data sources,
such as spreadsheets or flat files. With a JDBC technology-enabled driver, you can connect all
corporate data even in a heterogeneous environment

2 Q What are stored procedures?

y.rajashekher@gmail.com Page 91
A A stored procedure is a set of statements/commands which reside in the database. The stored
procedure is precompiled. Each Database has it's own stored procedure language,

3 Q What is JDBC Driver ?


A The JDBC Driver provides vendor-specific implementations of the abstract classes provided
by the JDBC API. This driver is used to connect to the database.

4 Q What are the steps required to execute a query in JDBC?


A First we need to create an instance of a JDBC driver or load JDBC drivers, then we need to
register this driver with DriverManager class. Then we can open a connection. By using this
connection , we can create a statement object and this object will help us to execute the query.

5 Q What is DriverManager ?
A DriverManager is a class in java.sql package. It is the basic service for managing a set of
JDBC drivers.

6 Q What is a ResultSet ?
A A table of data representing a database result set, which is usually generated by executing a
statement that queries the database.

A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is
positioned before the first row. The next method moves the cursor to the next row, and because it
returns false when there are no more rows in the ResultSet object, it can be used in a while loop
to iterate through the result set.

7 Q What is Connection?
A Connection class represents a connection (session) with a specific database. SQL statements
are executed and results are returned within the context of a connection.

A Connection object's database is able to provide information describing its tables, its supported
SQL grammar, its stored procedures, the capabilities of this connection, and so on. This
information is obtained with the getMetaData method.

8 Q What does Class.forName return?


A A class as loaded by the classloader.

9 Q What is Connection pooling?


A Connection pooling is a technique used for sharing server resources among requesting
clients. Connection pooling increases the performance of Web applications by reusing active
database connections instead of creating a new connection with every request. Connection pool
manager maintains a pool of open database connections.

10 Q What are the different JDB drivers available?


A There are mainly four type of JDBC drivers available. They are:

y.rajashekher@gmail.com Page 92
Type 1 : JDBC-ODBC Bridge Driver - A JDBC-ODBC bridge provides JDBC API access via
one or more ODBC drivers. Note that some ODBC native code and in many cases native
database client code must be loaded on each client machine that uses this type of driver. Hence,
this kind of driver is generally most appropriate when automatic installation and downloading of
a Java technology application is not important. For information on the JDBC-ODBC bridge
driver provided by Sun.

Type 2: Native API Partly Java Driver- A native-API partly Java technology-enabled driver
converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other
DBMS. Note that, like the bridge driver, this style of driver requires that some binary code be
loaded on each client machine.

Type 3: Network protocol Driver- A net-protocol fully Java technology-enabled driver translates
JDBC API calls into a DBMS-independent net protocol which is then translated to a DBMS
protocol by a server. This net server middleware is able to connect all of its Java technology-
based clients to many different databases. The specific protocol used depends on the vendor. In
general, this is the most flexible JDBC API alternative. It is likely that all vendors of this
solution will provide products suitable for Intranet use. In order for these products to also support
Internet access they must handle the additional requirements for security, access through
firewalls, etc., that the Web imposes. Several vendors are adding JDBC technology-based drivers
to their existing database middleware products.

Type 4: JDBC Net pure Java Driver - A native-protocol fully Java technology-enabled driver
converts JDBC technology calls into the network protocol used by DBMSs directly. This allows
a direct call from the client machine to the DBMS server and is a practical solution for Intranet
access. Since many of these protocols are proprietary the database vendors themselves will be
the primary source for this style of driver. Several database vendors have these in progress.

11 Q What is the fastest type of JDBC driver?


A Type 4 (JDBC Net pure Java Driver) is the fastest JDBC driver. Type 1 and Type 3 drivers
will be slower than Type 2 drivers (the database calls are make at least three translations versus
two), and Type 4 drivers are the fastest (only one translation).

12 Q Is the JDBC-ODBC Bridge multi-threaded?


A No. The JDBC-ODBC Bridge does not support multi threading. The JDBC-ODBC Bridge
uses synchronized methods to serialize all of the calls that it makes to ODBC. Multi-threaded
Java programs may use the Bridge, but they won't get the advantages of multi-threading.

13 Q What is cold backup, hot backup, warm backup recovery?


A Cold backup means all these files must be backed up at the same time, before the database is
restarted. Hot backup (official name is 'online backup' ) is a backup taken of each tablespace
while the database is running and is being accessed by the users

y.rajashekher@gmail.com Page 93
14 Q What is the advantage of denormalization?

A Data denormalization is reverse procedure, carried out purely for reasons of improving
performance. It maybe efficient for a high-throughput system to replicate data for certain data.

15 Q How do you handle your own transaction ?


A Connection Object has a method called setAutocommit ( boolean flag) . For handling our own
transaction we can set the parameter to false and begin your transaction . Finally commit the
transaction by calling the commit method.
========================== ***************** =========================

1. What are the steps involved in establishing a JDBC connection? This action involves
two steps: loading the JDBC driver and making the connection.
2. How can you load the drivers?
Loading the driver or drivers you want to use is very simple and involves just one line of
code. If, for example, you want to use the JDBC-ODBC Bridge driver, the following
code will load it:

Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);

Your driver documentation will give you the class name to use. For instance, if the class
name is jdbc.DriverXYZ, you would load the driver with the following line of code:

Class.forName(jdbc.DriverXYZ);

3. What will Class.forName do while loading drivers? It is used to create an instance of a


driver and register it with the
DriverManager. When you have loaded a driver, it is available for making a connection
with a DBMS.
4. How can you make the connection? To establish a connection you need to have the
appropriate driver connect to the DBMS.
The following line of code illustrates the general idea:

String url = jdbc:odbc:Fred;


Connection con = DriverManager.getConnection(url, Fernanda, J8?);

5. How can you create JDBC statements and what are they?
A Statement object is what sends your SQL statement to the DBMS. You simply create a
Statement object and then execute it, supplying the appropriate execute method with the
SQL statement you want to send. For a SELECT statement, the method to use is
executeQuery. For statements that create or modify tables, the method to use is
executeUpdate. It takes an instance of an active connection to create a Statement object.
In the following example, we use our Connection object con to create the Statement
object

y.rajashekher@gmail.com Page 94
Statement stmt = con.createStatement();

6. How can you retrieve data from the ResultSet?


JDBC returns results in a ResultSet object, so we need to declare an instance of the class
ResultSet to hold our results. The following code demonstrates declaring the ResultSet
object rs.

ResultSet rs = stmt.executeQuery(SELECT COF_NAME, PRICE FROM COFFEES);


String s = rs.getString(COF_NAME);

The method getString is invoked on the ResultSet object rs, so getString() will retrieve
(get) the value stored in the column COF_NAME in the current row of rs.

7. What are the different types of Statements?


Regular statement (use createStatement method), prepared statement (use
prepareStatement method) and callable statement (use prepareCall)
8. How can you use PreparedStatement? This special type of statement is derived from
class Statement.If you need a
Statement object to execute many times, it will normally make sense to use a
PreparedStatement object instead. The advantage to this is that in most cases, this SQL
statement will be sent to the DBMS right away, where it will be compiled. As a result, the
PreparedStatement object contains not just an SQL statement, but an SQL statement that
has been precompiled. This means that when the PreparedStatement is executed, the
DBMS can just run the PreparedStatements SQL statement without having to compile it
first.

PreparedStatement updateSales =
con.prepareStatement("UPDATE COFFEES SET SALES = ? WHERE
COF_NAME LIKE ?");

9. What does setAutoCommit do?


When a connection is created, it is in auto-commit mode. This means that each individual
SQL statement is treated as a transaction and will be automatically committed right after
it is executed. The way to allow two or more statements to be grouped into a transaction
is to disable auto-commit mode:

con.setAutoCommit(false);

Once auto-commit mode is disabled, no SQL statements will be committed until you call
the method commit explicitly.

con.setAutoCommit(false);
PreparedStatement updateSales =
con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE
COF_NAME LIKE ?");
updateSales.setInt(1, 50); updateSales.setString(2, "Colombian");
updateSales.executeUpdate();
PreparedStatement updateTotal =

y.rajashekher@gmail.com Page 95
con.prepareStatement("UPDATE COFFEES SET TOTAL = TOTAL + ? WHERE
COF_NAME LIKE ?");
updateTotal.setInt(1, 50);
updateTotal.setString(2, "Colombian");
updateTotal.executeUpdate();
con.commit();
con.setAutoCommit(true);

10. How do you call a stored procedure from JDBC?


The first step is to create a CallableStatement object. As with Statement an and
PreparedStatement objects, this is done with an open
Connection object. A CallableStatement object contains a call to a stored procedure.

CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");


ResultSet rs = cs.executeQuery();

11. How do I retrieve warnings?


SQLWarning objects are a subclass of SQLException that deal with database access
warnings. Warnings do not stop the execution of an
application, as exceptions do; they simply alert the user that something did not happen as
planned. A warning can be reported on a
Connection object, a Statement object (including PreparedStatement and
CallableStatement objects), or a ResultSet object. Each of these
classes has a getWarnings method, which you must invoke in order to see the first
warning reported on the calling object:

SQLWarning warning = stmt.getWarnings();


if (warning != null)
{
System.out.println("n---Warning---n");
while (warning != null)
{
System.out.println("Message: " + warning.getMessage());
System.out.println("SQLState: " + warning.getSQLState());
System.out.print("Vendor error code: ");
System.out.println(warning.getErrorCode());
System.out.println("");
warning = warning.getNextWarning();
}
}

12. How can you move the cursor in scrollable result sets?
One of the new features in the JDBC 2.0 API is the ability to move a result sets cursor
backward as well as forward. There are also methods that let you move the cursor to a
particular row and check the position of the cursor.

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,


ResultSet.CONCUR_READ_ONLY);
ResultSet srs = stmt.executeQuery(SELECT COF_NAME, PRICE FROM COFFEES);

y.rajashekher@gmail.com Page 96
The first argument is one of three constants added to the ResultSet API to indicate the
type of a ResultSet object: TYPE_FORWARD_ONLY,
TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE. The second
argument is one of two ResultSet constants for specifying whether a result set is read-
only or updatable: CONCUR_READ_ONLY and CONCUR_UPDATABLE. The point
to remember here is that if you specify a type, you must also specify whether it is read-
only or updatable. Also, you must specify the type first, and because both parameters are
of type int , the compiler will not complain if you switch the order. Specifying the
constant TYPE_FORWARD_ONLY creates a nonscrollable result set, that is, one in
which the cursor moves only forward. If you do not specify any constants for the type
and updatability of a ResultSet object, you will automatically get one that is
TYPE_FORWARD_ONLY and CONCUR_READ_ONLY.

13. Whats the difference between TYPE_SCROLL_INSENSITIVE , and


TYPE_SCROLL_SENSITIVE?
You will get a scrollable ResultSet object if you specify one of these ResultSet
constants.The difference between the two has to do with whether a result set reflects
changes that are made to it while it is open and whether certain methods can be called to
detect these changes. Generally speaking, a result set that is
TYPE_SCROLL_INSENSITIVE does not reflect changes made while it is still open and
one that is TYPE_SCROLL_SENSITIVE does. All three types of result sets will make
changes visible if they are closed and then reopened:

Statement stmt =

con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_
READ_ONLY);
ResultSet srs =
stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");
srs.afterLast();
while (srs.previous())
{
String name = srs.getString("COF_NAME");
float price = srs.getFloat("PRICE");
System.out.println(name + " " + price);
}

14. How to Make Updates to Updatable Result Sets?


Another new feature in the JDBC 2.0 API is the ability to update rows in a result set
using methods in the Java programming language rather than having to send an SQL
command. But before you can take advantage of this capability, you need to create a
ResultSet object that is updatable. In order to do this, you supply the ResultSet constant
CONCUR_UPDATABLE to the createStatement method.

Connection con =
DriverManager.getConnection("jdbc:mySubprotocol:mySubName");
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs =

y.rajashekher@gmail.com Page 97
stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");

========================== ***************** =========================


Java 1.5 - Features

Introduction

Time to open the Champagne - Java 1.5 is out, and the language has finally come of age! With
the new Java 1.5 specification, Java now contains features that make it feel like a proper 'grown-
up' language.

Compared to many other languages, such as FORTRAN and LISP, Java is a relative newcomer
on the scene. However, it has matured rapidly. It started out in 1995 as a simple C-like language
whose main advantages were automatic garbage collection and the ability to bring web pages to
life with applets. Early in the development of the World Wide Web, Sun and Netscape
announced that Java 1.0 would be included in Netscape Navigator, the most popular web
browser at the time. In 1997, Java 1.1 brought a more scaleable events model for the
programming of graphical user interfaces and the introduction of inner classes. Java 1.2 and 1.3
saw the introduction of the Collections framework, incremental improvements in Swing GUI
components, and the introduction of countless other libraries and Application Programmer
Interfaces (APIs), such as JavaMail and the Java Speech API. We also saw the rise of Java as a
server-side language, with Java Server Pages (JSPs) and Java Enterprise Beans. In 2002, Java 1.4
introduced assertions into the core language, and a logging facility.

But now (in a cinematic voice, and accompanied by a fanfare of trumpets) Sun has released Java
2, Standard Edition Developers' Kit, 1.5.0 Beta 1! Okay, it's still only a Beta release, so it's not a
package that you would use for serious software development, but it provides a great opportunity
to try out some of the latest feature offerings. This is the first major new release of Java in two
years and, in my opinion, it really brings the language forward. The changes are not just the
addition of new libraries, but the addition of the following new features to the language itself:

Type-Safe Enumerations
Static Import
Generics
Enhanced For Loop
Autoboxing/Unboxing
Varargs
MetaData

The rest of this article will introduce you to these new features. To try out the features for
yourself, simply download Java 1.5 from Sun's website and give it a whirl. Note that you'll need

y.rajashekher@gmail.com Page 98
to compile the code using the -source 1.5 option; otherwise, you'll get compilation errors
when using the new features.

Type-Safe Enumerations

Personally, the omission of 'proper' enumerations in earlier versions of Java really annoyed me. I
still can't believe how Java survived so long without it. In versions of Java prior to 1.5, the
typical approach to represent the suit of a playing card would be something like the following:

public interface CardSuit {


public static final int HEARTS = 0;
public static final int SPADES = 1;
public static final int CLUBS = 2;
public static final int DIAMONDS = 3;
}

The problem is that this representation is not type-safe: it is too easy to mix up an int that
represents the suit of a card with another int such as a loop counter. It could be made type-safe
by writing a class with a private constructor:

public class CardSuit {


public static final Suit HEARTS = new Suit();
public static final Suit SPADES = new Suit();
public static final Suit CLUBS = new Suit();
public static final Suit DIAMONDS = new Suit();

private Suit() {}
}

In this case, the only instances of the class Suit that will ever exist are those that are created
inside the class itself. It guarantees type-safety, but is long-winded and not easy to read. In Java
1.5, you can create an enumerated type in a single line as follows:

public enum CardSuit { hearts, spades, clubs, diamonds };

Think of the 'enum' keyword as an alternative to 'class', as similar restrictions apply. As with
classes, public enumerations must be in a file named after the enumeration, but the same
restriction does not apply to package level enumerations. Inner enumerations (if that is the
correct terminology) are also permitted, and can be public:

package card;

public class Card {

y.rajashekher@gmail.com Page 99
public enum CardValue { ace, two, three, four, five, six, seven, eight, nine, ten, jack, queen,
king };

private CardSuit suit;


private CardValue value;

public Card(CardValue newValue, CardSuit newSuit) {


suit = newSuit;
value = newValue;
}

public CardSuit getSuit() {


return suit;
}

public CardValue getValue() {


return value;
}

public String toString() {


return value+" of "+suit;
}
}

You can refer to the inner enumeration and its allowed values using the dot notation:
Card.CardValue.ace, for example.

Static Import

If you take exception to such lengthy references, in Java1.5 you can now use a 'static import':

import static card.Card.CardValue.*;


import static card.CardSuit.*;

This makes all the values defined for CardSuit and CardValue available to the importing class as
if they were defined in the same class. For example:

Card sixHearts = new Card(six, hearts);

Static imports can be used to import static identifiers and static methods as well as enumerations.

y.rajashekher@gmail.com Page 100


Generics

Something that I always found irksome about Java was the difference in the strength of typing
between arrays and collections. If an array of objects is used to hold some data, then every object
in the array has to be a (direct or indirect) instance of the same class. Any attempt to assign an
object of some other class to an element of the array results in a compile-time error. On the other
hand if a collection is used in Java 1.4 or earlier, then it is a (weakly-typed) collection of Objects.
This means that assigning an object of some other class to an element of the collection is
perfectly acceptable to the compiler, even though it may not have been the intention of the
programmer. Such situations give rise to a run-time error (typically a
ClassCastException). In other words, the use of collections placed an additional burden
on the programmer to avoid run-time errors that could not occur when arrays were used. The
programmer was faced with a trade-off between the flexibility of collections and the type-safety
of arrays. The good news is that this trade-off no longer exists! From Java 1.5, collections can be
strongly typed.

Instead of saying:

List deck = new ArrayList();

and (at most) commenting the intention that the List is to contain only objects of the class
Card, we can now enforce that constraint programmatically:

List<Card> deck = new ArrayList<Card>();

There is much more to be said about generics than can be covered in this article, but the basic
idea should be clear. For more information, take a look at Sun's Generics Tutorial.

Enhanced For Loop

It is common to iterate through Collections, yet the Java idiom for doing so has, until now, been
a little cumbersome. We would have to declare an Iterator, explicitly check whether another
object is available (as a loop condition), and then retrieve the object if there is one available. And
there's that tricky cast to contend with too.

Java 1.5 has simplified the idiom, so that, for example, instead of writing:

private void printCards(Collection deck) {


Iterator iter = deck.iterator();
while (iter.hasNext()) {
Card card = (Card) iter.next();
System.out.println(card.toString());
}
}

y.rajashekher@gmail.com Page 101


you can now write:

private void printCards(Collection<Card> deck) {


for (Card card : deck) {
System.out.println(card.toString());
}
}

This saves a bit of typing but, more importantly, is less error-prone. I certainly welcome the
omission of the cast.

You can also use the enhanced for-loop for iterating through arrays. I omitted to mention in the
earlier section on enumerations that the method values() can be applied to an enumeration to
retrieve an array of all the possible values. So using the new for-loop construct you can create a
deck of cards with:

List<Card> deck = new ArrayList<Card>();

for (CardSuit suit : CardSuit.values()) {


for (CardValue val : CardValue.values()) {
Card card = new Card(val, suit);
deck.add(card);
}
}

Auto-boxing/Auto-Unboxing

The idea of auto-boxing and auto-unboxing is to make it easier to convert between primitive data
types like int and boolean, and their equivalent Classes, like Integer and Boolean. It is
sometimes frustrating to have to do such a conversion, especially if the purpose of the conversion
is just for a method call, after which the results must be converted back to their original form
again.

For example, this feature allows you to write the following:

boolean result = Boolean.TRUE && Boolean.FALSE;

Previously, this would have generated the following error:

operator && cannot be applied to java.lang.Boolean,java.lang.Boolean


boolean result = Boolean.TRUE && Boolean.FALSE;
^

y.rajashekher@gmail.com Page 102


With Java 1.5, however, the Booleans are automatically converted to booleans before the
&& operator is applied.

The next example shows ints automatically being converted to Integers to store on a
Stack, then automatically being converted back again to perform the addition and store the
result in the variable stackSum.

import java.util.Stack;

Stack<Integer> myStack = new Stack<Integer>();


myStack.push(1);
myStack.push(2);
int stackSum = myStack.pop() + myStack.pop();
System.out.println(stackSum);

VarArgs

Another new feature is the ability to define methods that accept a variable number of arguments.
For example:

private void printCards(Card ... cards) {


for (Card card : cards) {
System.out.println(card.toString());
}
}

In a sense, this is syntactic sugar, because the formal parameter to the method is just an array. On
the other hand, this is exactly what you would need for a conventional formatted print method,
like the printf statement of C. And indeed, Java 1.5 does include such a method! The printCards
method above can be rewritten as:

private void printCards(Card ... cards) {


for (Card card : cards) {
System.out.printf("%s of %s\n", card.getSuit(), card.getValue());
}
}

Here, the printCards method accepts a variable number of arguments and the printf method call
also uses a VarArgs method call. The '%s' in the format control string indicates that a value
should be inserted at that point, and the following strings are the strings to be inserted.

Meta-Data

The idea of the new Meta-Data facility is to add annotations to your code that do not alter its
semantics, but provide additional information that can be used by a compiler or other utilities.

y.rajashekher@gmail.com Page 103


An example of such an annotation that you probably use already is the @deprecated tag.
Marking a method as deprecated does not change the operation of the method, but does generate
a warning when the compiler encounters it.

Java 1.5 introduces a new tag, called @override, with which the programmer can explicitly
state the intention to override a method of the superclass. If the superclass contains no such
method, then the compiler generates an error:

public @Overrides String toSring() {


return value+" of "+suit;
}

In this example, I missed out the 't' of 'String' in the method name, so that the method in fact does
not in fact override the toString() method of java.lang.Object. When the code is
compiled it produces the following error:

Card.java:22: method does not override a method from its superclass


public @Overrides String toSring() {
^
1 error

Defining your own tags to contain meta-data is somewhat more involved, and is therefore an
activity that most Java programmers will eschew. On the other hand, I can imagine that once tags
are defined, they would be used by large numbers of programmers. Depending on how the meta-
data facility is configured, annotations can be available in the source-code, at compile-time, or
even in the class files, accessible through Java reflection. This promises rich and powerful sets of
annotations that can be used at different stages of the development lifecycle for many different
purposes.

Conclusions

There are some other new features too. The features that I found most interesting are the
following:

extensions to JDBC RowSets to provide caching and filtering;


two new look-and-feels - Synth, a skinnable look and feel, and Ocean, a new theme for Metal;
there is now printing support for the Swing JTable.
improved diagnostic abilities: using Thread.getStackTrace(), it is now possible to
programmatically generate a stack trace as an array of StackTraceElements. .

========================== ***************** =========================


Other References:
http://www.roseindia.net/interviewquestions/
http://javapapers.com/interview-questions/java-interview-questions/
http://www.java-interview.com/Core_Java_Interview_Questions.html

y.rajashekher@gmail.com Page 104


http://www.java-interview.com/java_interview_questions.html
http://www.java-interview.com/jdbc_interview_questions.html
http://www.techinterviews.com/index.php?cat=4
http://www.geekinterview.com/Interview-Questions/J2EE/Core-Java
http://www.coolinterview.com/type.asp?iType=33
http://faqs.javabeat.net/java/core-java-interview-questions.php
http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html
========================== ***************** =========================

y.rajashekher@gmail.com Page 105

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