Documente Academic
Documente Profesional
Documente Cultură
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.
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.
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).
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.
Some examples of profiles within the Java 2 Platform, Micro Edition are:
* 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.
The program compiles properly but at runtime it will give Main method not public. message.
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 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 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.
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?
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
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.
The Java API is a large collection of ready-made software components that provide many useful
capabilities, such as graphical user interface (GUI) widgets.
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.
Global variables are globally accessible. Java does not support globally accessible variables due to
following reasons:
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();
int id = Integer.parseInt(numString);
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.
The Locale class is used to tailor a program output to the conventions of a particular geographic, political,
or cultural region.
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
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.
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.
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
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.
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.
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;
Explicit casting in the process in which the complier are specifically informed to about transforming the
object.
Example
long i = 700.20;
y.rajashekher@gmail.com Page 22
Is sizeof a keyword in java?
System is a predefined final class, out is a PrintStream object and println is a built-in overloaded method
in the out object.
The Java Virtual Machine is software that can be ported onto various hardware-based platforms
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 is the difference between public, private, protected and default Access Specifiers? Or
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
Object is the super class for all classes.( It is also called as the Cosmic super class.)
The 8 primitive types are byte, char, short, int, long, float, double, and boolean.
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.
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.
It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.
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.
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.
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.
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.
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.
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.
We can have multiple overloaded main methods but there can be only one main method with the
following signature :
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.
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.
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:
for example:
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.
Phantom memory is false memory. Memory that does not exist in reality.
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) {
Example:
while (st.hasMoreTokens()) {
y.rajashekher@gmail.com Page 26
System.out.println(st.nextToken());
Output:
Hello
World
y.rajashekher@gmail.com Page 27
Q: Difference between Vector and ArrayList?
A: Vector is synchronized whereas arraylist is not.
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.
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: 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 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.
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: 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 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.
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: 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...
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.
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: 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.
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: 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.
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.
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.
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.
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 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)
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 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.
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 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.
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.
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
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.
String objects are immutable whereas StringBuffer objects are not. StringBuffer unlike Strings support
growable and modifiable strings.
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.
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.
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.
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.
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.
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
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.
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.
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.
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.
A class does not inherit constructors from any of its super classes.
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.
The purpose of the Runtime class is to provide access to the Java runtime system.
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.
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.
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?
test1()
{ cntr++;
if(cntr>2)
System.out.println(hello 1);
System.out.println(hello 2);
An Object May not have a class definition. eg int a[] where a is an array.
my is an instance.
y.rajashekher@gmail.com Page 44
It is a memory area which stores all the objects created by an executing program.
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?
1.new operator
3.newInstance
4.object.clone
Class: A class is a user defined data type with set of data members & member functions
Instance: This represents the values of data members of a class at a particular time
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.
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:
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,
The class must provide all of the methods in the interface and identify the interface in its implements
clause.
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.
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();
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.
y.rajashekher@gmail.com Page 47
abstract class AbstractClassExample{
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.
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.
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:
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());
}
}
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
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().
It is a daemon thread.
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.
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?
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: 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.
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.
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.
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.
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.
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.
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 {
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
Errors are irrecoverable exceptions. Usually a program terminates when an error is encountered.
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.
Throwable
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
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?
Q: What are different ways in which a thread can enter the waiting state?
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
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.
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.
The wait(), notify() and notifyAll() methods are used to provide an efficient way for thread inter-
communication.
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.
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.
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
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.
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 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 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.
}
}
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.
y.rajashekher@gmail.com Page 55
Synchronized blocks place locks for shorter periods than synchronized methods.
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.
Yes, a lock can be acquired on a class. This lock is acquired on the classs Class object.
This class is an generic implementation of a thread pool, which takes the following input
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.
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.
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
y.rajashekher@gmail.com Page 57
A: The SimpleTimeZone class provides support for a Gregorian calendar .
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 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.
Yes a Vector can contain heterogenous objects. Because a Vector stores everything in
terms of Object
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.
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.
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.
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.
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.
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.
The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do
not allow duplicate elements.
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.
y.rajashekher@gmail.com Page 60
The Map interface is used associate keys with values.
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.
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.
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.
Yes you can limit the initial capacity. We can construct an empty vector with specified initial capacity
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.
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: 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.
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.
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.
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: 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);
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:
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.
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).
A. You can't force GC, but could request it by calling System.gc(). JVM does not guarantee that GC
will be started immediately.
A. If you assign a superclass object to a variable of a subclass's data type, you need to do explicit
casting. For example:
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?
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. 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.
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?
* 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?
* Q17. What can go wrong if you replace && with & in the following code:
y.rajashekher@gmail.com Page 67
A. This method is used to ensure that Swing components are updated through the event-
dispatching thread.
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?
** 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.
Answer : Yes, We can call a abstract method from a Non abstract method in a Java
abstract class
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.
Neither
Abstra
ct
classes
or
Interfa
ce can
be
instanti
ated.
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:
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.
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).
Answer: You can't force GC, but could request it by calling System.gc(). JVM does not
guarantee that GC will be started immediately.
Answer: If you assign a superclass object to a variable of a subclass's data type, you need to do
explicit casting. For example:
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: 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: 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.
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?
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?
Question: Can an inner class declared inside of a method access local variables of this
method?
Question: What can go wrong if you replace && with & in the following code: String
a=null; if (a!=null && a.length()>10) {...}
Answer: This method is used to ensure that Swing components are updated through the event-
dispatching thread.
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.
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?
y.rajashekher@gmail.com Page 73
Question: What comes to mind when someone mentions a shallow copy in Java?
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?
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 .
Answer: When i want child class to implement the behavior of the 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.
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
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 - 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 } } );
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.
Question: What is Runnable interface ? Are there any other ways to make a java program as
multithred java program?
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(); }
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.
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.
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.
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
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.
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
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 ?
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
(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
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.
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.
Answer: The EventObject class and the EventListener interface support event processing.
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).
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.
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.
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.
Answer: A native method is a method that is implemented in a language other than Java.
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
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.
Answer: The CheckboxMenuItem class extends the MenuItem class to support a menu item that
may be checked or unchecked.
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.
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.
Answer: An anonymous class may implement an interface or extend a superclass, but may not
be declared to do both.
y.rajashekher@gmail.com Page 83
Answer: The range of the short type is -(2^15) to 2^15 - 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.
Answer: MenuItem
Answer: 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 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 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 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.
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.
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.
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.
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.
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.
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();
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.
y.rajashekher@gmail.com Page 88
13.What are callable statements ?
Callable statements are used from JDBC application to invoke stored procedures and functions.
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.
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.
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
20.What is resultset ?
The ResultSet represents set of rows retrieved due to query execution.
ResultSet rs = stmt.executeQuery(sqlQuery);
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.
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.
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.
26.What is a DataSource?
A DataSource object is the representation of a data source in the Java programming language. In basic
terms,
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
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,
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.
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.
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.
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);
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();
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.
PreparedStatement updateSales =
con.prepareStatement("UPDATE COFFEES SET SALES = ? WHERE
COF_NAME LIKE ?");
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);
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.
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.
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);
}
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");
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:
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:
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:
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;
y.rajashekher@gmail.com Page 99
public enum CardValue { ace, two, three, four, five, six, seven, eight, nine, ten, jack, queen,
king };
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':
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:
Static imports can be used to import static identifiers and static methods as well as enumerations.
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:
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:
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.
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:
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:
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.
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;
VarArgs
Another new feature is the ability to define methods that accept a variable number of arguments.
For example:
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:
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.
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:
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:
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: