Vous êtes sur la page 1sur 103

1.

The byte code is executed by the Java runtime-systems which is called Java
Virtual Machine (JVM).
2. JVM is platform dependent.
3. JVM is not platform independent.
4. 'static' keyword allows main() to be called without instantiating a particular
instance of a cl
5. 'String args()' tells a parameter named args,which is an instance array of
class String
6. JVM is an interpreter of bytecode.
7. Bytecode extends with .class.
8. 'javac' compiler translates the .java file into .class.
9. JVM interprete bytecode.
10.
Bytecode facility makes Java platform-independent.
1. The Java programming language consists out of a Java compiler, the Java virtual
machine, and the Java class libraries. The Java virtual machine (JVM) is a software
implementation of a computer that executes programs like a real machine.
2. The Java compiler translates Java coding into so-called byte-code. The Java virtual
machine interprets this byte-code and runs the program.
3. The Java virtual machine is written specifically for a specific operating system.
4. The Java runtime environment (JRE) consists of the JVM and the Java class libraries.
5. Java is an object-oriented programming language and much of the syntax of Java is the
same as C and C++. One major difference is that Java does not have pointers.

Java Packages
Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and
annotations ) providing access protection and name space management.
Some of the existing packages in Java are::

java.lang - bundles the fundamental classes

java.io - classes for input , output functions are bundled in this package

Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a good
practice to group related classes implemented by you so that a programmer can easily determine that the
classes, interfaces, enumerations, annotations are related.
Since the package creates a new namespace there won't be any name conflicts with names in other
packages. Using packages, it is easier to provide access control and it is also easier to locate the related
classes.
1

To make types easier to find and use, to avoid naming conflicts, and to control access,
programmers bundle groups of related types into packages.
Definition: A package is a grouping of related types providing access protection and
name space management. Note that types refers to classes, interfaces, enumerations, and
annotation types. Enumerations and annotation types are special kinds of classes and
interfaces, respectively, so types are often referred to in this lesson simply as classes and
interfaces.
The types that are part of the Java platform are members of various packages that bundle
classes by function: fundamental classes are in java.lang, classes for reading and writing
(input and output) are in java.io, and so on.

What Is a Package?
A package is a namespace that organizes a set of related classes and interfaces. Conceptually you can
think of packages as being similar to different folders on your computer. You might keep HTML pages
in one folder, images in another, and scripts or applications in yet another. Because software written in
the Java programming language can be composed of hundreds or thousands of individual classes, it
makes sense to keep things organized by placing related classes and interfaces into packages.
The Java platform provides an enormous class library (a set of packages) suitable for use in your own
applications. This library is known as the "Application Programming Interface", or "API" for short. Its
packages represent the tasks most commonly associated with general-purpose programming. For
example, a String object contains state and behavior for character strings; a File object allows a
programmer to easily create, delete, inspect, compare, or modify a file on the filesystem; a Socket
object allows for the creation and use of network sockets; various GUI objects control buttons and
checkboxes and anything else related to graphical user interfaces. There are literally thousands of classes
to choose from. This allows you, the programmer, to focus on the design of your particular application,
rather than the infrastructure required to make it work.
The Java Platform API Specification contains the complete listing for all packages, interfaces, classes,
fields, and methods supplied by the Java SE platform. Load the page in your browser and bookmark it.
As a programmer, it will become your single most important piece of reference documentation.
A Java package is a technique for organizing Java classes into namespaces similar to the
modules of Modula, providing modular programming in Java.[1] Java packages can be
stored in compressed files called JAR files, allowing classes to be downloaded faster as
groups rather than individually. Programmers also typically use packages to organize
classes belonging to the same category or providing similar functionality. A package
provides a unique namespace for the types it contains. Classes in the same package can
access each other's package-private and protected members.

In a Java source file, the package that this file's class or classes belong to is specified with the package
keyword. This keyword is usually the first keyword in the source file. [2] At most one package declaration
can appear in a source file.
package java.awt.event;

To use a package's classes inside a Java source file, it is convenient to import the classes from the
package with an import declaration. The following declaration
import java.awt.event.*;
imports all classes from the java.awt.event
import java.awt.event.ActionEvent;

package, while the next declaration

imports only the ActionEvent class from the package. After either of these import declarations, the
ActionEvent class can be referenced using its simple class name:
ActionEvent myEvent = new ActionEvent();

Classes can also be used directly without an import declaration by using the fully qualified name of the
class. For example,
java.awt.event.ActionEvent myEvent = new java.awt.event.ActionEvent();

does not require a preceding import declaration.


Note that if you do not use a package declaration, your class ends up in an unnamed package. [3][4] Classes
in an unnamed package cannot be imported by classes in any other package.[5]

Package access protection


Public members and classes are visible everywhere and private members are visible only in the same
class. Classes within a package can access classes and members declared with default (package-private)
access as well as class members declared with the protected access modifier. Default (package-private)
access is enforced when a class or member has not been declared as public, protected or private. By
contrast, classes in other packages cannot access classes and members declared with default access.
However, class members declared as protected can be accessed from the classes in the same package
as well as classes in other packages that are subclasses of the declaring class.[6]

Package naming conventions


Packages are usually defined using a hierarchical naming pattern, with some levels in the hierarchy
separated by periods (., pronounced "dot"). Although packages lower in the naming hierarchy are often
referred to as "subpackages" of the corresponding packages higher in the hierarchy, there is almost no
semantic relationship between packages. The Java Language Specification establishes package naming
conventions to avoid the possibility of two published packages having the same name. The naming
conventions describe how to create unique package names, so that packages that are widely distributed
will have unique namespaces. This allows packages to be separately, easily and automatically installed
and catalogued.
In general, a package name begins with the top level domain name of the organization and then the
organization's domain and then any subdomains, listed in reverse order. The organization can then
choose a specific name for its package. Subsequent components of the package name vary according to
an organization's own internal naming conventions.[7]
For example, if an organization in Canada called MySoft creates a package to deal with fractions,
naming the package ca.mysoft.fractions distinguishes the fractions package from another similar
package created by another company. If a German company named MySoft also creates a fractions
package, but names it de.mysoft.fractions, then the classes in these two packages are defined in a
unique and separate namespace.
Complete conventions for disambiguating package names and rules for naming packages when the
Internet domain name cannot be directly used as a package name are described in section 7.7 of the Java
Language Specification.
3

Core packages in Java SE 6


java.lang
basic language functionality and fundamental types
java.util
collection data structure classes
java.io
file operations
java.math
multiprecision arithmetics
java.nio
the Non-Blocking I/O framework for Java
java.net
networking operations, sockets, DNS lookups, ...
java.security key generation, encryption and decryption
java.sql
Java Database Connectivity (JDBC) to access databases
java.awt
basic hierarchy of packages for native GUI components
javax.swing
hierarchy of packages for platform-independent rich GUI components
java.applet
classes for creating an applet
The java.lang package is available without the use of an import statement.

Java Platform, Standard Edition 7 API Specification


java.applet

Provides the classes necessary to create an applet and


the classes an applet uses to communicate with its
applet context.

java.awt

Contains all of the classes for creating user interfaces


and for painting graphics and images.

java.awt.color

Provides classes for color spaces.

java.awt.datatransfer

Provides interfaces and classes for transferring data


between and within applications.

java.awt.dnd

Drag and Drop is a direct manipulation gesture found


in many Graphical User Interface systems that
provides a mechanism to transfer information
between two entities logically associated with
presentation elements in the GUI.

java.awt.event

Provides interfaces and classes for dealing with


different types of events fired by AWT components.

java.awt.font

Provides classes and interface relating to fonts.

java.awt.geom

Provides the Java 2D classes for defining and


performing operations on objects related to twodimensional geometry.

java.awt.im

Provides classes and interfaces for the input method


framework.

java.awt.im.spi

Provides interfaces that enable the development of


input methods that can be used with any Java
runtime environment.

java.awt.image

Provides classes for creating and modifying images.

java.awt.image.renderable

Provides classes and interfaces for producing


rendering-independent images.
4

java.awt.print

Provides classes and interfaces for a general printing


API.

java.beans

Contains classes related to developing beans -components based on the JavaBeans architecture.

java.beans.beancontext

Provides classes and interfaces relating to bean


context.

java.io

Provides for system input and output through data


streams, serialization and the file system.

java.lang

Provides classes that are fundamental to the design


of the Java programming language.

java.lang.annotation

Provides library support for the Java programming


language annotation facility.

java.lang.instrument

Provides services that allow Java programming


language agents to instrument programs running on
the JVM.

java.lang.invoke

The java.lang.invoke package contains dynamic


language support provided directly by the Java core
class libraries and virtual machine.

java.lang.management

Provides the management interfaces for monitoring


and management of the Java virtual machine and
other components in the Java runtime.

java.lang.ref

Provides reference-object classes, which support a


limited degree of interaction with the garbage
collector.

java.lang.reflect

Provides classes and interfaces for obtaining


reflective information about classes and objects.

java.math

Provides classes for performing arbitrary-precision


integer arithmetic (BigInteger) and arbitraryprecision decimal arithmetic (BigDecimal).

java.net

Provides the classes for implementing networking


applications.

java.nio

Defines buffers, which are containers for data, and


provides an overview of the other NIO packages.

java.nio.channels

Defines channels, which represent connections to


entities that are capable of performing I/O
operations, such as files and sockets; defines
selectors, for multiplexed, non-blocking I/O
operations.

java.nio.channels.spi

Service-provider classes for the java.nio.channels


package.

java.nio.charset

Defines charsets, decoders, and encoders, for


translating between bytes and Unicode characters.

java.nio.charset.spi

Service-provider classes for the java.nio.charset


5

package.
java.nio.file

Defines interfaces and classes for the Java virtual


machine to access files, file attributes, and file
systems.

java.nio.file.attribute

Interfaces and classes providing access to file and


file system attributes.

java.nio.file.spi

Service-provider classes for the java.nio.file


package.

java.rmi

Provides the RMI package.

java.rmi.activation

Provides support for RMI Object Activation.

java.rmi.dgc

Provides classes and interface for RMI distributed


garbage-collection (DGC).

java.rmi.registry

Provides a class and two interfaces for the RMI


registry.

java.rmi.server

Provides classes and interfaces for supporting the


server side of RMI.

java.security

Provides the classes and interfaces for the security


framework.

java.security.acl

The classes and interfaces in this package have been


superseded by classes in the java.security package.

java.security.cert

Provides classes and interfaces for parsing and


managing certificates, certificate revocation lists
(CRLs), and certification paths.

java.security.interfaces

Provides interfaces for generating RSA (Rivest,


Shamir and Adleman AsymmetricCipher algorithm)
keys as defined in the RSA Laboratory Technical
Note PKCS#1, and DSA (Digital Signature
Algorithm) keys as defined in NIST's FIPS-186.

java.security.spec

Provides classes and interfaces for key specifications


and algorithm parameter specifications.

java.sql

Provides the API for accessing and processing data


stored in a data source (usually a relational database)
using the Java programming language.
TM

java.text

Provides classes and interfaces for handling text,


dates, numbers, and messages in a manner
independent of natural languages.

java.text.spi

Service provider classes for the classes in the


java.text package.

java.util

Contains the collections framework, legacy


collection classes, event model, date and time
facilities, internationalization, and miscellaneous
utility classes (a string tokenizer, a random-number
generator, and a bit array).
6

java.util.concurrent

Utility classes commonly useful in concurrent


programming.

java.util.concurrent.atomic

A small toolkit of classes that support lock-free


thread-safe programming on single variables.

java.util.concurrent.locks

Interfaces and classes providing a framework for


locking and waiting for conditions that is distinct
from built-in synchronization and monitors.

java.util.jar

Provides classes for reading and writing the JAR


(Java ARchive) file format, which is based on the
standard ZIP file format with an optional manifest
file.

java.util.logging

Provides the classes and interfaces of the Java 2


platform's core logging facilities.

java.util.prefs

This package allows applications to store and


retrieve user and system preference and
configuration data.

java.util.regex

Classes for matching character sequences against


patterns specified by regular expressions.

java.util.spi

Service provider classes for the classes in the


java.util package.

java.util.zip

Provides classes for reading and writing the standard


ZIP and GZIP file formats.

javax.accessibility

Defines a contract between user-interface


components and an assistive technology that
provides access to those components.

TM

javax.activation
javax.activity

Contains Activity service related exceptions thrown


by the ORB machinery during unmarshalling.

javax.annotation
javax.annotation.processing

Facilities for declaring annotation processors and for


allowing annotation processors to communicate with
an annotation processing tool environment.

javax.crypto

Provides the classes and interfaces for cryptographic


operations.

javax.crypto.interfaces

Provides interfaces for Diffie-Hellman keys as


defined in RSA Laboratories' PKCS #3.

javax.crypto.spec

Provides classes and interfaces for key specifications


and algorithm parameter specifications.

javax.imageio

The main package of the Java Image I/O API.

javax.imageio.event

A package of the Java Image I/O API dealing with


synchronous notification of events during the reading
and writing of images.

javax.imageio.metadata

A package of the Java Image I/O API dealing with


7

reading and writing metadata.


javax.imageio.plugins.bmp

Package containing the public classes used by the


built-in BMP plug-in.

javax.imageio.plugins.jpeg

Classes supporting the built-in JPEG plug-in.

javax.imageio.spi

A package of the Java Image I/O API containing the


plug-in interfaces for readers, writers, transcoders,
and streams, and a runtime registry.

javax.imageio.stream

A package of the Java Image I/O API dealing with


low-level I/O from files and streams.

javax.jws
javax.jws.soap
javax.lang.model

Classes and hierarchies of packages used to model


the Java programming language.

javax.lang.model.element

Interfaces used to model elements of the Java


programming language.

javax.lang.model.type

Interfaces used to model Java programming language


types.

javax.lang.model.util

Utilities to assist in the processing of program


elements and types.

javax.management

Provides the core classes for the Java Management


Extensions.

javax.management.loading

Provides the classes which implement advanced


dynamic loading.

javax.management.modelmbean

Provides the definition of the ModelMBean classes.

javax.management.monitor

Provides the definition of the monitor classes.

javax.management.openmbean

Provides the open data types and Open MBean


descriptor classes.

javax.management.relation

Provides the definition of the Relation Service.

javax.management.remote

Interfaces for remote access to JMX MBean servers.

javax.management.remote.rmi

The RMI connector is a connector for the JMX


Remote API that uses RMI to transmit client requests
to a remote MBean server.

javax.management.timer

Provides the definition of the Timer MBean.

javax.naming

Provides the classes and interfaces for accessing


naming services.

javax.naming.directory

Extends the javax.naming package to provide


functionality for accessing directory services.

javax.naming.event

Provides support for event notification when


accessing naming and directory services.

javax.naming.ldap

Provides support for LDAPv3 extended operations


and controls.
8

javax.naming.spi
javax.net

Provides classes for networking applications.

javax.net.ssl

Provides classes for the secure socket package.

javax.print

Provides the principal classes and interfaces for the


Java Print Service API.

javax.print.attribute

Provides classes and interfaces that describe the


types of Java Print Service attributes and how they
can be collected into attribute sets.

javax.print.attribute.standard

Package javax.print.attribute.standard contains


classes for specific printing attributes.

javax.print.event

Package javax.print.event contains event classes and


listener interfaces.

javax.rmi

Contains user APIs for RMI-IIOP.

javax.rmi.CORBA

Contains portability APIs for RMI-IIOP.

javax.rmi.ssl

Provides implementations of
RMIClientSocketFactory and
RMIServerSocketFactory over the Secure Sockets
Layer (SSL) or Transport Layer Security (TLS)
protocols.

javax.script

The scripting API consists of interfaces and classes


that define Java Scripting Engines and provides a
framework for their use in Java applications.

javax.security.auth

This package provides a framework for


authentication and authorization.

javax.security.auth.callback

This package provides the classes necessary for


services to interact with applications in order to
retrieve information (authentication data including
usernames or passwords, for example) or to display
information (error and warning messages, for
example).

javax.security.auth.kerberos

This package contains utility classes related to the


Kerberos network authentication protocol.

javax.security.auth.login

This package provides a pluggable authentication


framework.

javax.security.auth.spi

This package provides the interface to be used for


implementing pluggable authentication modules.

javax.security.auth.x500

This package contains the classes that should be used


to store X500 Principal and X500 Private
Crendentials in a Subject.

javax.security.cert

Provides classes for public key certificates.

javax.security.sasl

Contains class and interfaces for supporting SASL.

javax.sound.midi

Provides interfaces and classes for I/O, sequencing,


and synthesis of MIDI (Musical Instrument Digital

TM

TM

TM

Interface) data.
javax.sound.midi.spi

Supplies interfaces for service providers to


implement when offering new MIDI devices, MIDI
file readers and writers, or sound bank readers.

javax.sound.sampled

Provides interfaces and classes for capture,


processing, and playback of sampled audio data.

javax.sound.sampled.spi

Supplies abstract classes for service providers to


subclass when offering new audio devices, sound file
readers and writers, or audio format converters.

javax.sql

Provides the API for server side data source access


and processing from the Java programming
language.

javax.sql.rowset

Standard interfaces and base classes for JDBC


RowSet implementations.

javax.sql.rowset.serial

Provides utility classes to allow serializable


mappings between SQL types and data types in the
Java programming language.

javax.sql.rowset.spi

The standard classes and interfaces that a third party


vendor has to use in its implementation of a
synchronization provider.

javax.swing

Provides a set of "lightweight" (all-Java language)


components that, to the maximum degree possible,
work the same on all platforms.

javax.swing.border

Provides classes and interface for drawing


specialized borders around a Swing component.

javax.swing.colorchooser

Contains classes and interfaces used by the


JColorChooser component.

javax.swing.event

Provides for events fired by Swing components.

javax.swing.filechooser

Contains classes and interfaces used by the


JFileChooser component.

javax.swing.plaf

Provides one interface and many abstract classes that


Swing uses to provide its pluggable look-and-feel
capabilities.

javax.swing.plaf.basic

Provides user interface objects built according to the


Basic look and feel.

javax.swing.plaf.metal

Provides user interface objects built according to the


Java look and feel (once codenamed Metal), which is
the default look and feel.

javax.swing.plaf.multi

Provides user interface objects that combine two or


more look and feels.

javax.swing.plaf.nimbus

Provides user interface objects built according to the


cross-platform Nimbus look and feel.

javax.swing.plaf.synth

Synth is a skinnable look and feel in which all

TM

10

painting is delegated.
javax.swing.table

Provides classes and interfaces for dealing with


javax.swing.JTable.

javax.swing.text

Provides classes and interfaces that deal with


editable and noneditable text components.

javax.swing.text.html

Provides the class HTMLEditorKit and supporting


classes for creating HTML text editors.

javax.swing.text.html.parser

Provides the default HTML parser, along with


support classes.

javax.swing.text.rtf

Provides a class (RTFEditorKit) for creating RichText-Format text editors.

javax.swing.tree

Provides classes and interfaces for dealing with


javax.swing.JTree.

javax.swing.undo

Allows developers to provide support for undo/redo


in applications such as text editors.

javax.tools

Provides interfaces for tools which can be invoked


from a program, for example, compilers.

javax.transaction

Contains three exceptions thrown by the ORB


machinery during unmarshalling.

javax.transaction.xa

Provides the API that defines the contract between


the transaction manager and the resource manager,
which allows the transaction manager to enlist and
delist resource objects (supplied by the resource
manager driver) in JTA transactions.

javax.xml
javax.xml.bind

Provides a runtime binding framework for client


applications including unmarshalling, marshalling,
and validation capabilities.

javax.xml.bind.annotation

Defines annotations for customizing Java program


elements to XML Schema mapping.

javax.xml.bind.annotation.adapters

and its spec-defined sub-classes to


allow arbitrary Java classes to be used with JAXB.
XmlAdapter

javax.xml.bind.attachment

This package is implemented by a MIME-based


package processor that enables the interpretation and
creation of optimized binary data within an MIMEbased package format.

javax.xml.bind.helpers

JAXB Provider Use Only: Provides partial default


implementations for some of the javax.xml.bind
interfaces.

javax.xml.bind.util

Useful client utility classes.

javax.xml.crypto

Common classes for XML cryptography.

javax.xml.crypto.dom

DOM-specific classes for the javax.xml.crypto


package.
11

javax.xml.crypto.dsig

Classes for generating and validating XML digital


signatures.

javax.xml.crypto.dsig.dom

DOM-specific classes for the


javax.xml.crypto.dsig package.

javax.xml.crypto.dsig.keyinfo

Classes for parsing and processing KeyInfo elements


and structures.

javax.xml.crypto.dsig.spec

Parameter classes for XML digital signatures.

javax.xml.datatype

XML/Java Type Mappings.

javax.xml.namespace

XML Namespace processing.

javax.xml.parsers

Provides classes allowing the processing of XML


documents.

javax.xml.soap

Provides the API for creating and building SOAP


messages.

javax.xml.stream
javax.xml.stream.events
javax.xml.stream.util
javax.xml.transform

This package defines the generic APIs for processing


transformation instructions, and performing a
transformation from source to result.

javax.xml.transform.dom

This package implements DOM-specific


transformation APIs.

javax.xml.transform.sax

This package implements SAX2-specific


transformation APIs.

javax.xml.transform.stax

Provides for StAX-specific transformation APIs.

javax.xml.transform.stream

This package implements stream- and URI- specific


transformation APIs.

javax.xml.validation

This package provides an API for validation of XML


documents.

javax.xml.ws

This package contains the core JAX-WS APIs.

javax.xml.ws.handler

This package defines APIs for message handlers.

javax.xml.ws.handler.soap

This package defines APIs for SOAP message


handlers.

javax.xml.ws.http

This package defines APIs specific to the HTTP


binding.

javax.xml.ws.soap

This package defines APIs specific to the SOAP


binding.

javax.xml.ws.spi

This package defines SPIs for JAX-WS.

javax.xml.ws.spi.http

Provides HTTP SPI that is used for portable


deployment of JAX-WS web services in
containers(for e.g.

javax.xml.ws.wsaddressing

This package defines APIs related to WS12

Addressing.
javax.xml.xpath

This package provides an object-model neutral API


for the evaluation of XPath expressions and access to
the evaluation environment.

org.ietf.jgss

This package presents a framework that allows


application developers to make use of security
services like authentication, data integrity and data
confidentiality from a variety of underlying security
mechanisms like Kerberos, using a unified API.

org.omg.CORBA

Provides the mapping of the OMG CORBA APIs to


the Java programming language, including the class
ORB, which is implemented so that a programmer can
use it as a fully-functional Object Request Broker
(ORB).

org.omg.CORBA_2_3

The CORBA_2_3 package defines additions to


existing CORBA interfaces in the Java[tm] Standard
Edition 6. These changes occurred in recent
revisions to the CORBA API defined by the OMG.
The new methods were added to interfaces derived
from the corresponding interfaces in the CORBA
package. This provides backward compatibility and
avoids breaking the JCK tests.

org.omg.CORBA_2_3.portable

Provides methods for the input and output of value


types, and contains other updates to the
org/omg/CORBA/portable package.

org.omg.CORBA.DynAnyPackage

Provides the exceptions used with the DynAny


interface (InvalidValue, Invalid, InvalidSeq,
and TypeMismatch).

org.omg.CORBA.ORBPackage

Provides the exception InvalidName, which is


thrown by the method
ORB.resolve_initial_references and the
exception InconsistentTypeCode, which is thrown
by the Dynamic Any creation methods in the ORB
class.

org.omg.CORBA.portable

Provides a portability layer, that is, a set of ORB


APIs that makes it possible for code generated by
one vendor to run on another vendor's ORB.

org.omg.CORBA.TypeCodePackage

Provides the user-defined exceptions BadKind and


Bounds, which are thrown by methods in in the class
TypeCode.

org.omg.CosNaming

Provides a naming service for Java IDL.

TM

This package contains the following classes, which


org.omg.CosNaming.NamingContextExtPackage are used in
org.omg.CosNaming.NamingContextExt:
org.omg.CosNaming.NamingContextPackage

This package contains Exception classes for the


13

org.omg.CosNaming

package.

org.omg.Dynamic

This package contains the Dynamic module specified


in the OMG Portable Interceptor specification,
http://cgi.omg.org/cgi-bin/doc?ptc/2000-08-06,
section 21.9.

org.omg.DynamicAny

Provides classes and interfaces that enable traversal


of the data value associated with an any at runtime,
and extraction of the primitive constituents of the
data value.

org.omg.DynamicAny.DynAnyFactoryPackage

This package contains classes and exceptions from


the DynAnyFactory interface of the DynamicAny
module specified in the OMG The Common Object
Request Broker: Architecture and Specification,
http://cgi.omg.org/cgi-bin/doc?formal/99-10-07,
section 9.2.2.

org.omg.DynamicAny.DynAnyPackage

This package contains classes and exceptions from


the DynAny interface of the DynamicAny module
specified in the OMG The Common Object Request
Broker: Architecture and Specification,
http://cgi.omg.org/cgi-bin/doc?formal/99-10-07,
section 9.2.

org.omg.IOP

This package contains the IOP module specified in


the OMG document The Common Object Request
Broker: Architecture and Specification,
http://cgi.omg.org/cgi-bin/doc?formal/99-10-07,
section 13.6.

org.omg.IOP.CodecFactoryPackage

This package contains the exceptions specified in the


IOP::CodeFactory interface (as part of the Portable
Interceptors spec).

org.omg.IOP.CodecPackage

This package is generated from the IOP::Codec IDL


interface definition.

org.omg.Messaging

This package contains the Messaging module


specified in the OMG CORBA Messaging
specification, http://cgi.omg.org/cgi-bin/doc?
formal/99-10-07.

org.omg.PortableInterceptor

Provides a mechanism to register ORB hooks


through which ORB services can intercept the
normal flow of execution of the ORB.

This package contains the exceptions and typedefs


from the ORBInitInfo local interface of the
org.omg.PortableInterceptor.ORBInitInfoPackag PortableInterceptor module specified in the
e
OMG Portable Interceptor specification,
http://cgi.omg.org/cgi-bin/doc?ptc/2000-08-06,
section 21.7.2.
org.omg.PortableServer

Provides classes and interfaces for making the server


14

side of your applications portable across multivendor


ORBs.
org.omg.PortableServer.CurrentPackage

Provides method implementations with access to the


identity of the object on which the method was
invoked.

org.omg.PortableServer.POAManagerPackage

Encapsulates the processing state of the POAs it is


associated with.

org.omg.PortableServer.POAPackage

Allows programmers to construct object


implementations that are portable between different
ORB products.

org.omg.PortableServer.portable

Provides classes and interfaces for making the server


side of your applications portable across multivendor
ORBs.

org.omg.PortableServer.ServantLocatorPackage

Provides classes and interfaces for locating the


servant.

org.omg.SendingContext

Provides support for the marshalling of value types.

org.omg.stub.java.rmi

Contains RMI-IIOP Stubs for the Remote types that


occur in the java.rmi package.

org.w3c.dom

Provides the interfaces for the Document Object


Model (DOM) which is a component API of the Java
API for XML Processing.

org.w3c.dom.bootstrap
org.w3c.dom.events
org.w3c.dom.ls
org.xml.sax

This package provides the core SAX APIs.

org.xml.sax.ext

This package contains interfaces to SAX2 facilities


that conformant SAX drivers won't necessarily
support.

org.xml.sax.helpers

This package contains "helper" classes, including


support for bootstrapping SAX-based applications.

Java(TM) EE 7 Specification APIs

javax.annotation

This package defines the common annotations.

javax.annotation.security

This package contains the security common annotations.

javax.annotation.sql
javax.batch.api

Provides APIs used by Batch artifacts.

javax.batch.api.chunk

Provides APIs used by artifacts in a Batch chunk step.

javax.batch.api.chunk.listener

Provides APIs defining listener artifacts for a Batch chunk


step.

javax.batch.api.listener

Provides APIs defining Batch job-level and step-level listener


artifacts.
15

javax.batch.api.partition

Provides APIs for artifacts specific to a Batch partitioned


step.

javax.batch.operations

Provides APIs for starting, managing, and viewing results of


Batch job executions, along with a set of exceptions.

javax.batch.runtime

Provides APIs for viewing the detailed outcomes and metrics


of Batch job executions.

javax.batch.runtime.context

Provides APIs for context classes allowing data sharing


across Batch artifacts within a job instance and within a step.

javax.decorator

Annotations relating to decorators.

javax.ejb

Contains the Enterprise JavaBeans classes and interfaces that


define the contracts between the enterprise bean and its
clients and between the enterprise bean and the EJB
container.

javax.ejb.embeddable

Defines the classes for the EJB Embeddable API.

javax.ejb.spi

Defines interfaces that are implemented by the EJB container.

javax.el

Provides the API for the Unified Expression Language 3.0

javax.enterprise.concurrent

Classes and interfaces for concurrent programming in Java


EE applications.

javax.enterprise.context

Annotations and interfaces relating to scopes and contexts.

javax.enterprise.context.spi

The custom context SPI.

javax.enterprise.deploy.model

Provides Tool Vendor implementation classes.

javax.enterprise.deploy.model.exception
Provides Tool Vendor exception implementation classes.
s
javax.enterprise.deploy.shared

Provides shared objects for Tool Vendor and Product Vendor


implementation classes.

javax.enterprise.deploy.shared.factories

Provides shared factory manager object for Tool Vendor and


Product Vendor implementation classes.

javax.enterprise.deploy.spi

Provides J2EE Product Vendor implementation classes.

javax.enterprise.deploy.spi.exceptions

Provides J2EE Product Vendor deployment exception


implementation classes.

javax.enterprise.deploy.spi.factories

Provides J2EE Product Vendor deployment factory


implementation classes.

javax.enterprise.deploy.spi.status

Provides J2EE Product Vendor deployment status


implementation classes.

javax.enterprise.event

Annotations and interfaces relating to events.

javax.enterprise.inject

Annotations relating to bean and stereotype definition, builtin qualifiers, and interfaces and classes relating to
programmatic lookup.

javax.enterprise.inject.spi

The portable extension integration SPI.

javax.enterprise.util

Contains shared, general-purpose helper classes and


annotations.
16

javax.faces

Top level classes for the JavaServer(tm) Faces API.

javax.faces.application

APIs that are used to link an application's business logic


objects to JavaServer Faces, as well as convenient pluggable
mechanisms to manage the execution of an application that is
based on JavaServer Faces.

javax.faces.bean

These javadoc files constitute the Faces Managed Bean


Annotation Specification for Containers Conforming to
Servlet 2.5 and Beyond

javax.faces.component

Fundamental APIs for user interface components.

javax.faces.component.behavior

APIs for attaching additional behavior to user interface


components.

javax.faces.component.html

Specialized user interface component classes for HTML.

javax.faces.component.visit

APIs for traversing a user interface component view.

javax.faces.context

Classes and interfaces defining per-request state information.

javax.faces.convert

Contains classes and interfaces defining converters.

javax.faces.el

DEPRECATED Classes and interfaces for evaluating and


processing reference expressions.

javax.faces.event

Interfaces describing events and event listeners, and concrete


event implementation classes.

javax.faces.flow

The runtime API for Faces Flows.

javax.faces.flow.builder

Classes for declaring a Faces Flow.

javax.faces.lifecycle

Classes and interfaces defining lifecycle management for the


JavaServer Faces implementation.

javax.faces.model

Standard model data beans for JavaServer Faces.

javax.faces.render

Classes and interfaces defining the rendering model.

javax.faces.validator

Interface defining the validator model, and concrete validator


implementation classes.

javax.faces.view

Classes for defining a View Declaration Language (VDL) for


authoring JavaServer Faces user interfaces.

javax.faces.view.facelets

This package contains public classes for the Java code API of
Facelets.
17

javax.faces.webapp

Classes required for integration of JavaServer Faces into web


applications, including a standard servlet, base classes for
JSP custom component tags, and concrete tag
implementations for core tags.

javax.inject

This package specifies a means for obtaining objects in such


a way as to maximize reusability, testability and
maintainability compared to traditional approaches such as
constructors, factories, and service locators (e.g., JNDI). This
process, known as dependency injection, is beneficial to most
nontrivial applications.

javax.interceptor

Contains annotations and interfaces for defining interceptor


methods, interceptor classes and for binding interceptor
classes to target classes.

javax.jms

The Java Message Service (JMS) API provides a common


way for Java programs to create, send, receive and read an
enterprise messaging system's messages.

javax.json

Provides an object model API to process JSON.

javax.json.spi

Service Provider Interface (SPI) to plug in implementations


for JSON processing objects.

javax.json.stream

Provides a streaming API to parse and generate JSON.

javax.jws
javax.jws.soap
javax.mail

The JavaMail API provides classes that model a mail


system.

javax.mail.event

Listeners and events for the JavaMail API.

javax.mail.internet

Classes specific to Internet mail systems.

javax.mail.search

Message search terms for the JavaMail API.

javax.mail.util

JavaMail API utility classes.

javax.management.j2ee

Provides the J2EE Management Enterprise Bean component


(MEJB) interfaces.

javax.management.j2ee.statistics

Provides the standard interfaces for accessing performance


data from J2EE managed objects

javax.persistence

Java Persistence is the API for the management for


persistence and object/relational mapping.

javax.persistence.criteria

Java Persistence Criteria API

javax.persistence.metamodel

Java Persistence Metamodel API

javax.persistence.spi

SPI for Java Persistence providers

javax.resource

The javax.resource package is the top-level package for the


Java EE Connector API specification.

javax.resource.cci

The javax.resource.cci package contains API specification for


the Common Client Interface (CCI).

javax.resource.spi

The javax.resource.spi package contains APIs for the system

TM

18

contracts defined in the Java EE Connector Architecture


specification.
javax.resource.spi.endpoint

This package contains system contracts for service endpoint


interactions.

javax.resource.spi.security

The javax.resource.spi.security package contains APIs for the


security management contract.

javax.resource.spi.work

This package contains APIs for the Work Management,


Generic and Security Work Context contracts.

javax.security.auth.message

This package defines the core interfaces of the JSR 196


message authentication SPI.

javax.security.auth.message.callback

This package defines callback interfaces that may be used by


a pluggable message authentication module to interact with
the message processing runtime that invoked the module.

javax.security.auth.message.config

This package defines the interfaces implemented by JSR 196


compatible configuration systems.

javax.security.auth.message.module

This package defines the interfaces implemented by JSR 196


compatible authentication modules.

javax.security.jacc

This package contains the Java Authorization Contract for


Containers API

javax.servlet

The javax.servlet package contains a number of classes and


interfaces that describe and define the contracts between a
servlet class and the runtime environment provided for an
instance of such a class by a conforming servlet container.

javax.servlet.annotation

The javax.servlet.annotation package contains a number of


annotations that allow users to use annotations to declare
servlets, filters, listeners and specify the metadata for the
declared component.

javax.servlet.descriptor

Provides programmatic access to a web application's


configuration information that was aggregated from the
web.xml and web-fragment.xml descriptors.

javax.servlet.http

The javax.servlet.http package contains a number of classes


and interfaces that describe and define the contracts between
a servlet class running under the HTTP protocol and the
runtime environment provided for an instance of such a class
by a conforming servlet container.

javax.servlet.jsp

Classes and interfaces for the Core JSP 2.3 API.

javax.servlet.jsp.el

Provides the ELResolver classes that define the object


resolution rules that must be supported by a JSP container
with the new unified Expression Language.

javax.servlet.jsp.jstl.core

Classes and interfaces related to the core tag library


component of the JavaServer Pages Standard Tag Library
(JSTL).

javax.servlet.jsp.jstl.fmt

Classes and interfaces related to the locale sensitive


formatting tag library component of the JavaServer Pages
19

Standard Tag Library (JSTL).


javax.servlet.jsp.jstl.sql

Classes and interfaces related to the sql tag library


component of the JavaServer Pages Standard Tag Library
(JSTL).

javax.servlet.jsp.jstl.tlv

Reusable Tag Library Validator (TLV) classes provided by


the JavaServer Pages Standard Tag Library (JSTL).

javax.servlet.jsp.tagext

Classes and interfaces for the definition of JavaServer Pages


Tag Libraries.

javax.transaction

Provides the API that defines the contract between the


transaction manager and the various parties involved in a
distributed transaction namely : resource manager,
application, and application server.

javax.transaction.xa

Provides the API that defines the contract between the


transaction manager and the resource manager, which allows
the transaction manager to enlist and delist resource objects
(supplied by the resource manager driver) in JTA
transactions.

javax.validation

Top level package of the Bean Validation API.

javax.validation.bootstrap

Package containing bootstrap specific objects.

javax.validation.constraints

Contains all the Bean Validation provided constraints also


called built-in constraints.

javax.validation.constraintvalidation

Package containing constructs specific to constraint


validators In particular SupportedValidationTarget is
used to refine the validation target of a
ConstraintValidator.

javax.validation.executable

Package related to the control and execution of executable


validation.

javax.validation.groups

A group defines a subset of constraints.

javax.validation.metadata

Package containing all objects specifically used and returned


by the metadata API.

javax.validation.spi

Package containing objects specific to the interaction


between the Bean Validation bootstrapping process and Bean
Validation providers.

javax.websocket

This package contains all the WebSocket APIs common to


both the client and server side.

javax.websocket.server

This package contains all the WebSocket APIs used only by


server side applications.

javax.ws.rs

High-level interfaces and annotations used to create RESTful


service resources.

javax.ws.rs.client

The JAX-RS client API

javax.ws.rs.container

Container-specific JAX-RS API.

javax.ws.rs.core

Low-level interfaces and annotations used to create RESTful


service resources.
20

javax.ws.rs.ext

APIs that provide extensions to the types supported by the


JAX-RS API.

javax.xml.bind

Provides a runtime binding framework for client applications


including unmarshalling, marshalling, and validation
capabilities.

javax.xml.bind.annotation

Defines annotations for customizing Java program elements


to XML Schema mapping.

javax.xml.bind.annotation.adapters

and its spec-defined sub-classes to allow


arbitrary Java classes to be used with JAXB.
XmlAdapter

javax.xml.bind.attachment

This package is implemented by a MIME-based package


processor that enables the interpretation and creation of
optimized binary data within an MIME-based package
format.

javax.xml.bind.helpers

JAXB Provider Use Only: Provides partial default


implementations for some of the javax.xml.bind interfaces.

javax.xml.bind.util

Useful client utility classes.

javax.xml.registry

This package and its sub-packages describe the API classes


and interfaces for the JAXR API.

javax.xml.registry.infomodel

This package describes the information model for the JAXR


API.

javax.xml.rpc

This package contains the core JAX-RPC APIs for the client
programming model.

javax.xml.rpc.encoding

This package defines APIs for the extensible type mapping


framework.

javax.xml.rpc.handler

This package defines APIs for SOAP Message Handlers

javax.xml.rpc.handler.soap

This package defines APIs for SOAP Message Handlers

javax.xml.rpc.holders

This package contains the standard Java Holder classes.

javax.xml.rpc.server

This package defines APIs for the servlet based JAX-RPC


endpoint model.

javax.xml.rpc.soap

This package defines APIs specific to the SOAP binding.

javax.xml.soap

Provides the API for creating and building SOAP messages.

javax.xml.ws

This package contains the core JAX-WS APIs.

javax.xml.ws.handler

This package defines APIs for message handlers.

javax.xml.ws.handler.soap

This package defines APIs for SOAP message handlers.

javax.xml.ws.http

This package defines APIs specific to the HTTP binding.

javax.xml.ws.soap

This package defines APIs specific to the SOAP binding.

javax.xml.ws.spi

This package defines SPIs for JAX-WS.

javax.xml.ws.spi.http

Provides HTTP SPI that is used for portable deployment of


JAX-WS web services in containers(for e.g.

javax.xml.ws.wsaddressing

This package defines APIs related to WS-Addressing.


21

Access Specifiers In Java

Java Access Specifiers (also known as Visibility Specifiers ) regulate access to classes, fields and
methods in Java.These Specifiers determine whether a field or method in a class, can be used or invoked
by another method in another class or sub-class. Access Specifiers can be used to restrict access. Access
Specifiers are an integral part of object-oriented programming.
Types Of Access Specifiers :
In java we have four Access Specifiers and they are listed below.
1. public
2. private
3. protected
4. default(no specifier)
We look at these Access Specifiers in more detail.

public specifiers :
Public Specifiers achieves the highest level of accessibility. Classes, methods, and fields declared as
public can be accessed from any class in the Java program, whether these classes are in the same
package or in another package.
Example :
view plainprint?
1. public class Demo { // public class
2. public x, y, size; // public instance variables
3. }
private specifiers :
Private Specifiers achieves the lowest level of accessibility.private methods and fields can only be
22

accessed within the same class to which the methods and fields belong. private methods and fields are
not visible within subclasses and are not inherited by subclasses. So, the private access specifier is
opposite to the public access specifier. Using Private Specifier we can achieve encapsulation and hide
data from the outside world.
Example :
view plainprint?
1. public class Demo { // public class
2. private double x, y; // private (encapsulated) instance variables
3.
4. public set(int x, int y) { // setting values of private fields
5. this.x = x;
6. this.y = y;
7. }
8.
9. public get() { // setting values of private fields
10. return Point(x, y);
11. }
12. }
protected specifiers :
Methods and fields declared as protected can only be accessed by the subclasses in other package or any
class within the package of the protected members' class. The protected access specifier cannot be
applied to class and interfaces.
default(no specifier):
When you don't set access specifier for the element, it will follow the default accessibility level. There is
no default specifier keyword. Classes, variables, and methods can be default accessed.Using default
specifier we can access class, method, or field which belongs to same package,but not from outside this
package.
Example :
view plainprint?
23

1. class Demo
2. {
3. int i; (Default)
4. }
RealTimeExample

OOPS And Its Concepts Or Properties In Java

Definition :
OOPS stands for Object Oriented Programming.Object Oriented Programming is the technique to create
programs based on the real world. Unlike procedural programming, here in the OOP programming
model programs are organized around objects and data rather than actions and logic.
OOPS Concept :
OOPS reduce the code of the program because of the extensive Properties.OOPS
Properties or Concepts are mainly 4 and they are listed below.
1.Encapsulation
2.Abstraction
3.Inheritance
4.Polymorphisam
lets see in detail about the concepts of OOPS.
1. Encapsulation :
It 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. One way to think about encapsulation is as a
protective wrapper that prevents code and data from being arbitrarily accessed by other code defined
24

outside the wrapper. Idea of encapsulation is to hide how a class does it but to allow requesting what to
do.
Example : Medical Capsuals
i.e one drug is stored in Bottom layer and another drug is stored in Upper layer these two layers are
combined in single capsual.
2. Abstraction :

Hiding non-essential features and showing the essential features


(or)
Hiding unnecessary data from the users details,is called abstraction.
Example: TV Remote Button
i.e In TV Remote there are numbers, power and other buttons. We can just see those buttons,we don't see
the button circuits and wirings.so non-essential features are hidden from the user.
3. Inheritance :

25

creating a new class from existing class is called Inheritance.reusability is main advantage in
inheritance.The new classes, known as derived classes take over (or
inherit) attribute and behavior of the pre-existing classes,which are referred to as base classes (or Parent
classes).
Example : Father and Son Relationship
4.Polymorphisam :

The ability to take more than one form. The abiltiy to define more than one function with the same name
is called Polymorphism. In java there are two type of polymorphism.
a) compile time polymorphism (overloading)
b) runtime polymorphism (overriding).
What Is A Java Class ?

Java Class is nothing but a template for object you are going to create (or) its a blue print by using this
we create an object.
- In simple words we can say its a pattern which we define and every object we define will follow the
pattern. class are fundamental building.
What does Java Class Consist :

When you create class in java the first step is keyword class and then name of the class or
identifier we can say.
26

Next is class body which starts with curly braces { } and between this all things related with that
class means their property and method will come here.

Class Syntax :
<access specifier> class <identifier>
{
<member>
...
}
Access Specifiers Of Class :
Java class has mainly two type of access level and they are listed below.
Default: class objects are accessible only inside the package.
Public: class objects are accessible in code in any package.
Members of Class :
The contents of the body of a class consists of a collection of <members>. Members consist of fields and
methods.
Field : Things in the Java language which hold data, or hold pointers to objects are called fields. Think
of fields as variables.
Method : Method is a set of statement that perform a particular task. It is similar to function is c/c++.
Java - Files and I/O

The java.io package contains nearly every class you might ever need to perform input and output (I/O)
in Java. All these streams represent an input source and an output destination. The stream in the java.io
package supports many data such as primitives, Object, localized characters, etc.

Stream
A stream can be defined as a sequence of data. there are two kinds of Streams

InPutStream: The InputStream is used to read data from a source.

OutPutStream: the OutputStream is used for writing data to a destination.

27

Java provides strong but flexible support for I/O related to Files and networks but this tutorial covers
very basic functionality related to streams and I/O. We would see most commonly used example one by
one:

Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many classes
related to byte streams but the most frequently used classes are , FileInputStream and
FileOutputStream. Following is an example which makes use of these two classes to copy an input file
into an output file:
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException
{
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}

Now let's have a file input.txt with the following content:


This is test for copy file.

As a next step, compile above program and execute it, which will result in creating output.txt file with
the same content as we have in input.txt. So let's put above code in CopyFile.java file and do the
following:
$javac CopyFile.java
$java CopyFile

28

Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, where as Java Character streams
are used to perform input and output for 16-bit unicode. Though there are many classes related to
character streams but the most frequently used classes are , FileReader and FileWriter.. Though
internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here major
difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.
We can re-write above example which makes use of these two classes to copy an input file (having
unicode characters) into an output file:
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException
{
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}

Now let's have a file input.txt with the following content:


This is test for copy file.

As a next step, compile above program and execute it, which will result in creating output.txt file with
the same content as we have in input.txt. So let's put above code in CopyFile.java file and do the
following:
$javac CopyFile.java
$java CopyFile

Standard Streams
All the programming languages provide support for standard I/O where user's program can take input
from a keyboard and then produce output on the computer screen. If you are aware if C or C++
programming languages, then you must be aware of three standard devices STDIN, STDOUT and
STDERR. Similar way Java provides following three standard streams
29

Standard Input: This is used to feed the data to user's program and usually a keyboard is used
as standard input stream and represented as System.in.

Standard Output: This is used to output the data produced by the user's program and usually a
computer screen is used to standard output stream and represented as System.out.

Standard Error: This is used to output the error data produced by the user's program and
usually a computer screen is used to standard error stream and represented as System.err.

Following is a simple program which creates InputStreamReader to read standard input stream until
the user types a "q":
import java.io.*;
public class ReadConsole {
public static void main(String args[]) throws IOException
{
InputStreamReader cin = null;

try {
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
char c;
do {
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();
}
}

Let's keep above code in ReadConsole.java file and try to compile and execute it as below. This program
continues reading and outputting same character until we press 'q':
$javac ReadConsole.java
$java ReadConsole
Enter characters, 'q' to quit.
1
1
e
e
q
q

Reading and Writing Files:


As described earlier, A stream can be defined as a sequence of data. The InputStream is used to read
data from a source and the OutputStream is used for writing data to a destination.
Here is a hierarchy of classes to deal with Input and Output streams.
30

The two important streams are FileInputStream and FileOutputStream, which would be discussed in
this tutorial:

FileInputStream:
This stream is used for reading data from the files. Objects can be created using the keyword new and
there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the file.:
InputStream f = new FileInputStream("C:/java/hello");

Following constructor takes a file object to create an input stream object to read the file. First we create
a file object using File() method as follows:
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);

Once you have InputStream object in hand, then there is a list of helper methods which can be used to
read to stream or to do other operations on the stream.
S
N

Methods with Description


public void close() throws IOException{}

1 This method closes the file output stream. Releases any system resources associated with the file.

Throws an IOException.
protected void finalize()throws IOException {}
2 This method cleans up the connection to the file. Ensures that the close method of this file output

stream is called when there are no more references to this stream. Throws an IOException.
public int read(int r)throws IOException{}
3 This method reads the specified byte of data from the InputStream. Returns an int. Returns the next

byte of data and -1 will be returned if it's end of file.


public int read(byte[] r) throws IOException{}
4 This method reads r.length bytes from the input stream into an array. Returns the total number of

bytes read. If end of file -1 will be returned.


public int available() throws IOException{}
5

Gives the number of bytes that can be read from this file input stream. Returns an int.

There are other important input streams available, for more detail you can refer to the following links:
31

ByteArrayInputStream

DataInputStream

FileOutputStream:
FileOutputStream is used to create a file and write data into it. The stream would create a file, if it
doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object to write the file:
OutputStream f = new FileOutputStream("C:/java/hello")

Following constructor takes a file object to create an output stream object to write the file. First, we
create a file object using File() method as follows:
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);

Once you have OutputStream object in hand, then there is a list of helper methods, which can be used to
write to stream or to do other operations on the stream.
S
N

Methods with Description


public void close() throws IOException{}

1 This method closes the file output stream. Releases any system resources associated with the file.

Throws an IOException
protected void finalize()throws IOException {}
2 This method cleans up the connection to the file. Ensures that the close method of this file output

stream is called when there are no more references to this stream. Throws an IOException.
public void write(int w)throws IOException{}
3

This methods writes the specified byte to the output stream.


public void write(byte[] w)

Writes w.length bytes from the mentioned byte array to the OutputStream.

There are other important output streams available, for more detail you can refer to the following links:

ByteArrayOutputStream

DataOutputStream
32

Example:
Following is the example to demonstrate InputStream and OutputStream:
import java.io.*;
public class fileStreamTest{
public static void main(String args[]){
try{
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("test.txt");
for(int x=0; x < bWrite.length ; x++){
os.write( bWrite[x] ); // writes the bytes
}
os.close();
InputStream is = new FileInputStream("test.txt");
int size = is.available();
for(int i=0; i< size; i++){
System.out.print((char)is.read() + "
}
is.close();
}catch(IOException e){
System.out.print("Exception");
}
}

");

The above code would create file test.txt and would write given numbers in binary format. Same would
be output on the stdout screen.

File Navigation and I/O:


There are several other classes that we would be going through to get to know the basics of File
Navigation and I/O.

File Class

FileReader Class

FileWriter Class

Directories in Java:
A directory is a File which can contains a list of other files and directories. You use File object to create
directories, to list down files available in a directory. For complete detail check a list of all the methods
which you can call on File object and what are related to directories.

Creating Directories:
There are two useful File utility methods, which can be used to create directories:

33

The mkdir( ) method creates a directory, returning true on success and false on failure. Failure
indicates that the path specified in the File object already exists, or that the directory cannot be
created because the entire path does not exist yet.

The mkdirs() method creates both a directory and all the parents of the directory.

Following example creates "/tmp/user/java/bin" directory:


import java.io.File;
public class CreateDir {
public static void main(String args[]) {
String dirname = "/tmp/user/java/bin";
File d = new File(dirname);
// Create directory now.
d.mkdirs();
}
}

Compile and execute above code to create "/tmp/user/java/bin".


Note: Java automatically takes care of path separators on UNIX and Windows as per conventions. If you
use a forward slash (/) on a Windows version of Java, the path will still resolve correctly.

Listing Directories:
You can use list( ) method provided by File object to list down all the files and directories available in a
directory as follows:
import java.io.File;
public class ReadDir {
public static void main(String[] args) {
File file = null;
String[] paths;
try{
// create new file object
file = new File("/tmp");
// array of files and directory
paths = file.list();
// for each name in the path array
for(String path:paths)
{
// prints filename and directory name
System.out.println(path);
}
}catch(Exception e){
// if any error occurs
e.printStackTrace();
}
}

34

This would produce following result based on the directories and files available in your /tmp directory:
Java - Exceptions

An exception (or exceptional event) is a problem that arises during the execution of a program. When an
Exception occurs the normal flow of the program is disrupted and the program/Application terminates
abnormally, which is not recommended, therefore these exceptions are to be handled.
An exception can occur for many different reasons, below given are some scenarios where exception
occurs.

A user has entered invalid data.

A file that needs to be opened cannot be found.

A network connection has been lost in the middle of communications or the JVM has run out of
memory.

Some of these exceptions are caused by user error, others by programmer error, and others by physical
resources that have failed in some manner.
Based on these we have three categories of Exceptions you need to understand them to know how
exception handling works in Java,

Checked exceptions: A checked exception is an exception that occurs at the compile time, these
are also called as compile time exceptions. These exceptions cannot simply be ignored at the
time of compilation, the Programmer should take care of (handle) these exceptions.
For example, if you use FileReader class in your program to read data from a file, if the file
specified in its constructor doesn't exist, then an FileNotFoundException occurs, and compiler
prompts the programmer to handle the exception.

import java.io.File;
import java.io.FileReader;
public class FilenotFound_Demo {
public static void main(String args[]){
File file=new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}

If you try to compile the above program you will get exceptions as shown below.

C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be
caught or declared to be thrown
FileReader fr = new FileReader(file);

35

1 error

Note: Since the methods read() and close() of FileReader class throws IOException, you can observe
that compiler notifies to handle IOException, along with FileNotFoundException.

Unchecked exceptions: An Unchecked exception is an exception that occurs at the time of


execution, these are also called as Runtime Exceptions, these include programming bugs, such as
logic errors or improper use of an API. runtime exceptions are ignored at the time of compilation.
For example, if you have declared an array of size 5 in your program, and trying to call the 6th
element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs.

public class Unchecked_Demo {


public static void main(String args[]){
int num[]={1,2,3,4};
System.out.println(num[5]);
}
}

If you compile and execute the above program you will get exception as shown below.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)

Errors: These are not exceptions at all, but problems that arise beyond the control of the user or
the programmer. Errors are typically ignored in your code because you can rarely do anything
about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored
at the time of compilation.

Exception Hierarchy:
All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of
the Throwable class. Other than the exception class there is another subclass called Error which is
derived from the Throwable class.
Errors are abnormal conditions that happen in case of severe failures, these are not handled by the java
programs. Errors are generated to indicate errors generated by the runtime environment. Example : JVM
is out of Memory. Normally programs cannot recover from errors.
The Exception class has two main subclasses: IOException class and RuntimeException Class.

36

Here is a list of most common checked and unchecked Java's Built-in Exceptions.

Exceptions Methods:
Following is the list of important medthods available in the Throwable class.
S

Methods with Description


37

N
public String getMessage()
1 Returns a detailed message about the exception that has occurred. This message is initialized in the

Throwable constructor.
public Throwable getCause()
2

Returns the cause of the exception as represented by a Throwable object.


public String toString()

Returns the name of the class concatenated with the result of getMessage()
public void printStackTrace()

Prints the result of toString() along with the stack trace to System.err, the error output stream.
public StackTraceElement [] getStackTrace()

5 Returns an array containing each element on the stack trace. The element at index 0 represents the

top of the call stack, and the last element in the array represents the method at the bottom of the call
stack.
public Throwable fillInStackTrace()

6 Fills the stack trace of this Throwable object with the current stack trace, adding to any previous

information in the stack trace.

Catching Exceptions:
A method catches an exception using a combination of the try and catch keywords. A try/catch block is
placed around the code that might generate an exception. Code within a try/catch block is referred to as
protected code, and the syntax for using try/catch looks like the following:
try
{

//Protected code
}catch(ExceptionName e1)
{
//Catch block
}

The code which is prone to exceptions is placed in the try block, when an exception occurs, that
exception occurred is handled by catch block associated with it. Every try block should be immediately
followed either by a catch block or finally block.
A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs
in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that
38

occurred is listed in a catch block, the exception is passed to the catch block much as an argument is
passed into a method parameter.

Example:
The following is an array is declared with 2 elements. Then the code tries to access the 3rd element of
the array which throws an exception.
// File Name : ExcepTest.java
import java.io.*;
public class ExcepTest{

public static void main(String args[]){


try{
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}

This would produce the following result:


Exception thrown
Out of the block

:java.lang.ArrayIndexOutOfBoundsException: 3

Multiple catch Blocks:


A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the
following:
try
{

//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}

The previous statements demonstrate three catch blocks, but you can have any number of them after a
single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in
the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the
exception passes down to the second catch statement. This continues until the exception either is caught
or falls through all catches, in which case the current method stops execution and the exception is
thrown down to the previous method on the call stack.

Example:
Here is code segment showing how to use multiple try/catch statements.
39

try
{
file = new FileInputStream(fileName);
x = (byte) file.read();
}catch(IOException i)
{
i.printStackTrace();
return -1;
}catch(FileNotFoundException f) //Not valid!
{
f.printStackTrace();
return -1;
}

Catching multiple type of exceptions


Since Java 7 you can handle more than one exceptions using a single catch block, this feature simplifies
the code. Below given is the syntax of writing
catch (IOException|FileNotFoundException ex) {
logger.log(ex);
throw ex;

The throws/throw Keywords:


If a method does not handle a checked exception, the method must declare it using the throws keyword.
The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just caught, by
using the throw keyword.
Try to understand the difference between throws and throw keywords, throws is used to
postpone the handling of a checked exception and throw is used to invoke an exception
explicitly.

The following method declares that it throws a RemoteException:


import java.io.*;
public class className
{
public void deposit(double amount) throws RemoteException
{
// Method implementation
throw new RemoteException();
}
//Remainder of class definition
}

A method can declare that it throws more than one exception, in which case the exceptions are declared
in a list separated by commas. For example, the following method declares that it throws a
RemoteException and an InsufficientFundsException:
import java.io.*;
public class className
{
public void withdraw(double amount) throws RemoteException,

40

InsufficientFundsException

// Method implementation
}
//Remainder of class definition

The finally block


The finally block follows a try block or a catch block. A finally block of code always executes,
irrespective of occurrence of an Exception.
Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter
what happens in the protected code.
A finally block appears at the end of the catch blocks and has the following syntax:
try
{

//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}

Example:
public class ExcepTest{
public static void main(String args[]){
int a[] = new int[2];
try{
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
finally{
a[0] = 6;
System.out.println("First element value: " +a[0]);
System.out.println("The finally statement is executed");
}
}
}

This would produce the following result:


Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed

Note the following:


41

A catch clause cannot exist without a try statement.

It is not compulsory to have finally clauses when ever a try/catch block is present.

The try block cannot be present without either catch clause or finally clause.

Any code cannot be present in between the try, catch, finally blocks.

The try-with-resources
Generally when we use any resources like streams, connections etc.. we have to close them explicitly
using finally block. In the program given below we are reading data from a file using FileReader and
we are closing it using finally block.
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ReadData_Demo {
public static void main(String args[]){
FileReader fr=null;
try{
File file=new File("file.txt");
fr = new FileReader(file); char [] a = new char[50];
fr.read(a); // reads the content to the array
for(char c : a)
System.out.print(c); //prints the characters one by one
}catch(IOException e){
e.printStackTrace();
}
finally{
try{
fr.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
}
}

try-with-resources, also referred as automatic resource management. is a new exception handling


mechanism that was introduced in Java7, which automatically closes the resources used within the try
catch block.
To use this statement you simply need to declare the required resources within the parenthesis, the
created resource will be closed automatically at the end of the block, below given is the syntax of trywith-resources statement.
try(FileReader fr=new FileReader("file path"))
{
//use the resource
}catch(){
//body of catch

42

Below given is the program that reads the data in a file using try-with-resources statement.
import java.io.FileReader;
import java.io.IOException;
public class Try_withDemo {
public static void main(String args[]){
try(FileReader fr=new FileReader("E://file.txt")){
char [] a = new char[50];
fr.read(a); // reads the contentto the array
for(char c : a)
System.out.print(c); //prints the characters one by one
}catch(IOException e){
e.printStackTrace();
}
}

Following points are to be kept in mind while working with try-with resources statement.

To use a class with try-with-resources statement it should implement AutoCloseable interface


and the close() method of it gets invoked automatically at runtime.

You can declare more than one class in try-with-resources statement.

while you declare multiple classes in the try block of try-with-resources statement these classes
are closed in reverse order.

Except the deceleration of resources within the parenthesis every thing is same as normal
try/catch block of a try block.

The resource declared in try gets instantiated just before the start of the try-block.

The resource declared at the try block is implicitly declared as final.

User-defined Exceptions:
You can create your own exceptions in Java. Keep the following points in mind when writing your own
exception classes:

All exceptions must be a child of Throwable.

If you want to write a checked exception that is automatically enforced by the Handle or Declare
Rule, you need to extend the Exception class.

If you want to write a runtime exception, you need to extend the RuntimeException class.
43

We can define our own Exception class as below:


class MyException extends Exception{
}

You just need to extend the predefined Exception class to create your own Exception. These are
considered to be checked exceptions. The following InsufficientFundsException class is a user-defined
exception that extends the Exception class, making it a checked exception. An exception class is like any
other class, containing useful fields and methods.

Example:
// File Name InsufficientFundsException.java
import java.io.*;
public class InsufficientFundsException extends Exception
{
private double amount;
public InsufficientFundsException(double amount)
{
this.amount = amount;
}
public double getAmount()
{
return amount;
}
}

To demonstrate using our user-defined exception, the following CheckingAccount class contains a
withdraw() method that throws an InsufficientFundsException.
// File Name CheckingAccount.java
import java.io.*;
public class CheckingAccount
{
private double balance;
private int number;
public CheckingAccount(int number)
{
this.number = number;
}
public void deposit(double amount)
{
balance += amount;
}
public void withdraw(double amount) throws InsufficientFundsException
{
if(amount <= balance)
{
balance -= amount;
}
else
{
double needs = amount - balance;
throw new InsufficientFundsException(needs);

44

public double getBalance()


{
return balance;
}
public int getNumber()
{
return number;
}
}

The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of
CheckingAccount.
// File Name BankDemo.java
public class BankDemo
{
public static void main(String [] args)
{
CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing $500...");
c.deposit(500.00);
try
{

System.out.println("\nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
}catch(InsufficientFundsException e)
{
System.out.println("Sorry, but you are short $" + e.getAmount());
e.printStackTrace();
}

Compile all the above three files and run BankDemo, this would produce the following result:
Depositing $500...
Withdrawing $100...
Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)

Common Exceptions:
In Java, it is possible to define two catergories of Exceptions and Errors.

JVM Exceptions: - These are exceptions/errors that are exclusively or logically thrown by the
JVM. Examples : NullPointerException, ArrayIndexOutOfBoundsException,
ClassCastException,
45

Programmatic exceptions: - These exceptions are thrown explicitly by the application or the
API programmers Examples: IllegalArgumentException, IllegalStateException.

Java - Inner classes

Nested Classes
In Java, just like methods, variables of a class too can have another class as its member. Writing a class
within another is allowed in Java. The class written within is called the nested class, and the class that
holds the inner class is called the outer class.

Syntax
The syntax to write a nested class is given below. Here the class Outer_Demo is the outer class and the
class Inner_Demo is the nested class.
class Outer_Demo{
class Nested_Demo{
}
}

Nested classes are divided into two types:

Non-static nested classes: These are the non-static members of a class.

Static nested classes: These are the static members of a class.

46

Inner Classes (Non-static Nested Classes)


Inner classes are a security mechanism in Java. We know a class cannot be associated with the access
modifier private, but if we have the class as a member of other class, then the inner class can be made
private. And this is also used to access the private members of a class.
Inner classes are of three types depending on how and where you define them. They are:

Inner Class

Method-local Inner Classlass

Anonymous Inner Class

Inner Class
Creating an inner class is quite simple. You just need to write a class within a class. Unlike a class, an
inner class can be private and once you declare an inner class private, it cannot be accessed from an
object outside the class.
Given below is the program to create an inner class and access it. In the given example, we make the
inner class private and access the class through a method.
class Outer_Demo{
int num;
//inner class
private class Inner_Demo{{
public void print(){
System.out.println("This is an inner class");
}
}
//Accessing he inner class from the method within
void display_Inner(){
Inner_Demo inner = new Inner_Demo();
inner.print();
}
}
public class My_class{
public static void main(String args[]){
//Instantiating the outer class
Outer_Demo outer=new Outer_Dem();
//Accessing the display_Inner() method.
outer.display_Inner();
}
}

Here you can observe that Outer_Demo is the outer class, Inner_Demo is the inner class,
display_Inner() is the method inside which we are instantiating the inner class, and this method is
invoked from the main method.
If you compile and execute the above program, you will get the following result.
47

This is an inner class.

Accessing the Private Members

As mentioned earlier, inner classes are also used to access the private members of a class. Suppose a
class is having private members to access them. Write an inner class in it, return the private members
from a method within the inner class, say, getValue(), and finally from another class (from which you
want to access the private members) call the getValue() method of the inner class.
To instantiate the inner class, initially you have to instantiate the outer class. Thereafter, using the object
of the outer class, you can instantiate the inner class as shown below.
Outer_Demo outer=new Outer_Demo();
Outer_Demo.Inner_Demo inner=outer.new Inner_Demo();

The following program shows how to access the private members of a class using inner class.
class Outer_Demo {
//private variable of the outer class
private int num= 175;
//inner class
public class Inner_Demo{
public int getNum(){
System.out.println("This is the getnum method of the inner class");
return num;
}
}
}
public class My_class2{
public static void main(String args[]){
//Instantiating the outer class
Outer_Demo outer=new Outer_Demo();
//Instantiating the inner class
Outer_Demo.Inner_Demo inner=outer.new Inner_Demo();
System.out.println(inner.getNum());
}
}

If you compile and execute the above program, you will get the following result.
The value of num in the class Test is: 175

Method-local Inner Class


In Java, we can write a class within a method and this will be a local type. Like local variables, the scope
of the inner class is restricted within the method.
A method-local inner class can be instantiated only within the method where the inner class is defined.
The following program shows how to use a method-local inner class.
public class Outerclass{
//instance method of the outer class
void my_Method(){
int num=23;

48

//method-local inner class


class MethodInner_Demo{
public void print(){
System.out.println("This is method inner class "+num);
}
}//end of inner class
//Accessing the inner class
MethodInner_Demo inner=new MethodInner_Demo();
inner.print();
}
public static void main(String args[]){
Outerclass outer =new Outerclass();
outer.my_Method();
}
}

If you compile and execute the above program, you will get the following result.
This is method inner class 23

Anonymous Inner Class


An inner class declared without a class name is known as an anonymous inner class. In case of
anonymous inner classes, we declare and instantiate them at the same time. Generally they are used
whenever you need to override the method of a class or an interface. The syntax of an anonymous inner
class is as follows:
AnonymousInner an_inner= new AnonymousInner(){
public void my_method(){
........
........
}
};

The following program shows how to override the method of a class using anonymous inner class.
abstract class AnonymousInner{
public abstract void mymethod();
}
public class Outer_class {
public static void main(String args[]){
AnonymousInner inner= new AnonymousInner(){
public void mymethod(){
System.out.println("This is an example of anonymous inner class");
}
};
inner.mymethod();
}
}

If you compile and execute the above program, you will get the following result.
This is an example of anonymous inner class

In the same way, you can override the methods of the concrete class as well as the interface using an
anonymous inner class.
49

Anonymous Inner Class as Argument

Generally if a method accepts an object of an interface, an abstract class, or a concrete class, then we can
implement the interface, extend the abstract class, and pass the object to the method. If it is a class, then
we can directly pass it to the method.
But in all the three cases, you can pass an anonymous inner class to the method. Here is the syntax of
passing an anonymous inner class as a method argument:
obj.my_Method(new My_Class(){
public void Do(){
.....
.....
}
});

The following program shows how to pass an anonymous inner class as a method argument.
//interface
interface Message{
String greet();
}
public class My_class {
//method which accepts the object of interface Message
public void displayMessage(Message m){
System.out.println(m.greet() +", This is an example of anonymous inner calss
as an argument");
}
public static void main(String args[]){
//Instantiating the class
My_class obj=new My_class();
//Passing an anonymous inner class as an argument
obj.displayMessage(new Message(){
public String greet(){
return "Hello";
}
});
}
}

If you compile and execute the above program, it gives you the following result.
Hello This is an example of anonymous inner class as an argument

Static Nested Class


A static inner class is a nested class which is a static member of the outer class. It can be accessed
without instantiating the outer class, using other static members. Just like static members, a static nested
class does not have access to the instance variables and methods of the outer class. The syntax of static
nested class is as follows:
class MyOuter {
static class Nested_Demo{
}
}

50

Instantiating a static nested class is a bit different from instantiating an inner class. The following
program shows how to use a static nested class.
public class Outer{
static class Nested_Demo{
public void my_method(){
System.out.println("This is my nested class");
}
}
public static void main(String args[]){
Outer.Nested_Demo nested=new Outer.Nested_Demo();
nested.my_method();
}
}

Java - Inheritance

Inheritance can be defined as the process where one class acquires the properties (methods and fields) of
another. With the use of inheritance the information is made manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass (derived class, child class) and the
class whose properties are inherited is known as superclass (base class, parent class).

extends Keyword
extends is the keyword used to inherit the properties of a class. Below given is the syntax of extends
keyword.
class Super{
.....
.....
}
class Sub extends Super{
.....
.....
}

Sample Code
Below given is an example demonstrating Java inheritance. In this example you can observe two classes
namely Calculation and My_Calculation.
Using extends keyword the My_Calculation inherits the methods addition() and Subtraction() of
Calculation class.
Copy and paste the program given below in a file with name My_Calculation.java
class Calculation{
int z;
public void addition(int x, int y){

51

z = x+y;
System.out.println("The sum of the given numbers:"+z);
}
public void Substraction(int x,int y){
z = x-y;
System.out.println("The difference between the given numbers:"+z);
}
}
public class My_Calculation extends Calculation{
public void multiplication(int x, int y){
z = x*y;
System.out.println("The product of the given numbers:"+z);
}
public static void main(String args[]){
int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Substraction(a, b);
demo.multiplication(a, b);
}
}

Compile and execute the above code as shown below


javac My_Calculation.java
java My_Calculation

After executing the program it will produce the following result.


The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200

In the given program when an object to My_Calculation class is created, a copy of the contents of the
super class is made with in it. That is why, using the object of the subclass you can access the members
of a super class.

52

The Superclass reference variable can hold the subclass object, but using that variable you can access
only the members of the superclass, so to access the members of both classes it is recommended to
always create reference variable to the subclass.
If you consider the above program you can instantiate the class as given below as well. But using the
superclass reference variable ( cal in this case ) you cannot call the method multiplication(), which
belongs to the subclass My_Calculation.
Calculation cal = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);

Note A subclass inherits all the members (fields, methods, and nested classes) from its superclass.
Constructors are not members, so they are not inherited by subclasses, but the constructor of the
superclass can be invoked from the subclass.

The super keyword


The super keyword is similar to this keyword following are the scenarios where the super keyword is
used.

It is used to differentiate the members of superclass from the members of subclass, if they have
same names.

It is used to invoke the superclass constructor from subclass.

Differentiating the members

If a class is inheriting the properties of another class. And if the members of the superclass have the
names same as the sub class, to differentiate these variables we use super keyword as shown below.
super.variable
super.method();

Sample Code

This section provides you a program that demonstrates the usage of the super keyword.
In the given program you have two classes namely Sub_class and Super_class, both have a method
named display() with different implementations, and a variable named num with different values. We are
invoking display() method of both classes and printing the value of the variable num of both classes,
here you can observe that we have used super key word to differentiate the members of super class from
sub class.
Copy and paste the program in a file with name Sub_class.java.
class Super_class{
int num = 20;
//display method of superclass
public void display(){

53

System.out.println("This is the display method of superclass");

}
public class Sub_class extends Super_class {
int num = 10;
//display method of sub class
public void display(){
System.out.println("This is the display method of subclass");
}
public void my_method(){
//Instantiating subclass
Sub_class sub = new Sub_class();
//Invoking the display() method of sub class
sub.display();
//Invoking the display() method of superclass
super.display();
//printing the value of variable num of subclass
System.out.println("value of the variable named num in sub class:"+ sub.num);
//printing the value of variable num of superclass
System.out.println("value of the variable named num in super class:"+
super.num);
}
public static void main(String args[]){
Sub_class obj = new Sub_class();
obj.my_method();
}
}

Compile and execute the above code using the following syntax.
javac Super_Demo
java Super

On executing the program you will get the following result


This is the display method of subclass
This is the display method of superclass
value of the variable named num in sub class:10
value of the variable named num in super class:20

Invoking Superclass constructor

If a class is inheriting the properties of another class, the subclass automatically acquires the default
constructor of the super class. But if you want to call a parametrized constructor of the super class, you
need to use the super keyword as shown below.
super(values);

54

Sample Code

The program given in this section demonstrates how to use the super keyword to invoke the
parametrized constructor of the superclass. This program contains a super class and a sub class, where
the super class contains a parametrized constructor which accepts a string value, and we used the super
keyword to invoke the parametrized constructor of the super class.
Copy and paste the below given program in a file with name Subclass.java
class Superclass{
int age;
Superclass(int age){
this.age = age;
}
public void getAge(){
System.out.println("The value of the variable named age in super class is: "
+age);
}
}
public class Subclass extends Superclass {
Subclass(int age){
super(age);
}
public static void main(String argd[]){
Subclass s = new Subclass(24);
s.getAge();
}
}

Compile and execute the above code using the following syntax.
javac Subclass
java Subclass

On executing the program you will get the following result


The value of the variable named age in super class is: 24

IS-A Relationship
IS-A is a way of saying : This object is a type of that object. Let us see how the extends keyword is used
to achieve inheritance.
public class Animal{
}
public class Mammal extends Animal{
}
public class Reptile extends Animal{
}

55

public class Dog extends Mammal{


}

Now, based on the above example, In Object Oriented terms, the following are true

Animal is the superclass of Mammal class.

Animal is the superclass of Reptile class.

Mammal and Reptile are subclasses of Animal class.

Dog is the subclass of both Mammal and Animal classes.

Now, if we consider the IS-A relationship, we can say

Mammal IS-A Animal

Reptile IS-A Animal

Dog IS-A Mammal

Hence : Dog IS-A Animal as well

With use of the extends keyword the subclasses will be able to inherit all the properties of the superclass
except for the private properties of the superclass.
We can assure that Mammal is actually an Animal with the use of the instance operator.

Example
class Animal{
}
class Mammal extends Animal{
}
class Reptile extends Animal{
}
public class Dog extends Mammal{
public static void main(String args[]){
Animal a = new Animal();
Mammal m = new Mammal();
Dog d = new Dog();
System.out.println(m instanceof Animal);
System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}

56

This would produce the following result


true
true
true

Since we have a good understanding of the extends keyword let us look into how the implements
keyword is used to get the IS-A relationship.
Generally, the implements keyword is used with classes to inherit the properties of an interface.
Interfaces can never be extended by a class.

Example
public interface Animal {
}
public class Mammal implements Animal{
}
public class Dog extends Mammal{
}

The instanceof Keyword


Let us use the instanceof operator to check determine whether Mammal is actually an Animal, and dog
is actually an Animal
interface Animal{}
class Mammal implements Animal{}
public class Dog extends Mammal{
public static void main(String args[]){
Mammal m = new Mammal();
Dog d = new Dog();
System.out.println(m instanceof Animal);
System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}

This would produce the following result:


true
true
true

HAS-A relationship
These relationships are mainly based on the usage. This determines whether a certain class HAS-A
certain thing. This relationship helps to reduce duplication of code as well as bugs.
Lets us look into an example
57

public class Vehicle{}


public class Speed{}
public class Van extends Vehicle{
private Speed sp;
}

This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not have to put the
entire code that belongs to speed inside the Van class., which makes it possible to reuse the Speed class
in multiple applications.
In Object-Oriented feature, the users do not need to bother about which object is doing the real work. To
achieve this, the Van class hides the implementation details from the users of the Van class. So basically
what happens is the users would ask the Van class to do a certain action and the Van class will either do
the work by itself or ask another class to perform the action.

Types of inheritance
There are various types of inheritance as demonstrated below.

A very important fact to remember is that Java does not support multiple inheritance. This means that a
class cannot extend more than one class. Therefore following is illegal
public class extends Animal, Mammal{}

58

However, a class can implement one or more interfaces. This has made Java get rid of the impossibility
of multiple inheritance.
Java - Overriding

In the previous chapter, we talked about super classes and sub classes. If a class inherits a method from
its super class, then there is a chance to override the method provided that it is not marked final.
The benefit of overriding is: ability to define a behaviour that's specific to the subclass type which
means a subclass can implement a parent class method based on its requirement.
In object-oriented terms, overriding means to override the functionality of an existing method.

Example:
Let us look at an example.
class Animal{

public void move(){


System.out.println("Animals can move");
}

class Dog extends Animal{


public void move(){
System.out.println("Dogs can walk and run");
}
}
public class TestDog{
public static void main(String args[]){
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move();// runs the method in Animal class
}

b.move();//Runs the method in Dog class

This would produce the following result:


Animals can move
Dogs can walk and run

In the above example, you can see that the even though b is a type of Animal it runs the move method in
the Dog class. The reason for this is: In compile time, the check is made on the reference type. However,
in the runtime, JVM figures out the object type and would run the method that belongs to that particular
object.
Therefore, in the above example, the program will compile properly since Animal class has the method
move. Then, at the runtime, it runs the method specific for that object.
59

Consider the following example :


class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
System.out.println("Dogs can walk and run");
}
public void bark(){
System.out.println("Dogs can bark");
}
}
public class TestDog{
public static void main(String args[]){
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object

a.move();// runs the method in Animal class


b.move();//Runs the method in Dog class
b.bark();

This would produce the following result:


TestDog.java:30: cannot find symbol
symbol : method bark()
location: class Animal
b.bark();
^

This program will throw a compile time error since b's reference type Animal doesn't have a method by
the name of bark.

Rules for method overriding:

The argument list should be exactly the same as that of the overridden method.

The return type should be the same or a subtype of the return type declared in the original
overridden method in the superclass.

The access level cannot be more restrictive than the overridden method's access level. For
example: if the superclass method is declared public then the overridding method in the sub class
cannot be either private or protected.

Instance methods can be overridden only if they are inherited by the subclass.

A method declared final cannot be overridden.


60

A method declared static cannot be overridden but can be re-declared.

If a method cannot be inherited, then it cannot be overridden.

A subclass within the same package as the instance's superclass can override any superclass
method that is not declared private or final.

A subclass in a different package can only override the non-final methods declared public or
protected.

An overriding method can throw any uncheck exceptions, regardless of whether the overridden
method throws exceptions or not. However the overriding method should not throw checked
exceptions that are new or broader than the ones declared by the overridden method. The
overriding method can throw narrower or fewer exceptions than the overridden method.

Constructors cannot be overridden.

Using the super keyword:


When invoking a superclass version of an overridden method the super keyword is used.
class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
super.move(); // invokes the super class method
System.out.println("Dogs can walk and run");
}
}
public class TestDog{
public static void main(String args[]){
Animal b = new Dog(); // Animal reference but Dog object
b.move(); //Runs the method in Dog class
}
}

Java - Polymorphism

Polymorphism is the ability of an object to take on many forms. The most common use of
polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.

61

Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all Java
objects are polymorphic since any object will pass the IS-A test for their own type and for the class
Object.
It is important to know that the only possible way to access an object is through a reference variable. A
reference variable can be of only one type. Once declared, the type of a reference variable cannot be
changed.
The reference variable can be reassigned to other objects provided that it is not declared final. The type
of the reference variable would determine the methods that it can invoke on the object.
A reference variable can refer to any object of its declared type or any subtype of its declared type. A
reference variable can be declared as a class or interface type.

Example:
Let us look at an example.
public interface Vegetarian{}
public class Animal{}
public class Deer extends Animal implements Vegetarian{}

Now, the Deer class is considered to be polymorphic since this has multiple inheritance. Following are
true for the above example:

A Deer IS-A Animal

A Deer IS-A Vegetarian

A Deer IS-A Deer

A Deer IS-A Object

When we apply the reference variable facts to a Deer object reference, the following declarations are
legal:
Deer d = new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;

All the reference variables d,a,v,o refer to the same Deer object in the heap.

Virtual Methods:
In this section, I will show you how the behaviour of overridden methods in Java allows you to take
advantage of polymorphism when designing your classes.

62

We already have discussed method overriding, where a child class can override a method in its parent.
An overridden method is essentially hidden in the parent class, and is not invoked unless the child class
uses the super keyword within the overriding method.
/* File name : Employee.java */
public class Employee
{
private String name;
private String address;
private int number;
public Employee(String name, String address, int number)
{
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public void mailCheck()
{
System.out.println("Mailing a check to " + this.name
+ " " + this.address);
}
public String toString()
{
return name + " " + address + " " + number;
}
public String getName()
{
return name;
}
public String getAddress()
{
return address;
}
public void setAddress(String newAddress)
{
address = newAddress;
}
public int getNumber()
{
return number;
}
}

Now suppose we extend Employee class as follows:


/* File name : Salary.java */
public class Salary extends Employee
{
private double salary; //Annual salary
public Salary(String name, String address, int number, double
salary)
{
super(name, address, number);
setSalary(salary);
}
public void mailCheck()
{
System.out.println("Within mailCheck of Salary class ");

63

System.out.println("Mailing check to " + getName()


+ " with salary " + salary);

}
public double getSalary()
{
return salary;
}
public void setSalary(double newSalary)
{
if(newSalary >= 0.0)
{
salary = newSalary;
}
}
public double computePay()
{
System.out.println("Computing salary pay for " + getName());
return salary/52;
}

Now, you study the following program carefully and try to determine its output:
/* File name : VirtualDemo.java */
public class VirtualDemo
{
public static void main(String [] args)
{
Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();
System.out.println("\n Call mailCheck using Employee reference--");
e.mailCheck();
}
}

This would produce the following result:


Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference -Within mailCheck of Salary class
ailing check to Mohd Mohtashim with salary 3600.0
Call mailCheck using Employee reference-Within mailCheck of Salary class
ailing check to John Adams with salary 2400.0

Here, we instantiate two Salary objects . one using a Salary reference s, and the other using an Employee
reference e.
While invoking s.mailCheck() the compiler sees mailCheck() in the Salary class at compile time, and the
JVM invokes mailCheck() in the Salary class at run time.
Invoking mailCheck() on e is quite different because e is an Employee reference. When the compiler
sees e.mailCheck(), the compiler sees the mailCheck() method in the Employee class.
64

Here, at compile time, the compiler used mailCheck() in Employee to validate this statement. At run
time, however, the JVM invokes mailCheck() in the Salary class.
This behavior is referred to as virtual method invocation, and the methods are referred to as virtual
methods. All methods in Java behave in this manner, whereby an overridden method is invoked at run
time, no matter what data type the reference is that was used in the source code at compile time.
Java - Abstraction

As per dictionary, Abstraction is the quality of dealing with ideas rather than events. for example when
you consider the case of e-mail, complex details such as what happens soon you send an e-mail, the
protocol your email server uses are hidden from the user, therefore to send an e-mail you just need to
type the content, mention the address of the receiver and click send.
like wise in Object oriented programming Abstraction is a process process of hiding the implementation
details from the user, only the functionality will be provided to the user. In other words user will have
the information on what the object does instead of how it does it.
In Java Abstraction is achieved using Abstract classes, and Interfaces.

Abstract Class
A class which contains the abstract keyword in its declaration is known as abstract class.

Abstract classes may or may not contain abstract methods ie., methods with out body ( public
void get(); )

But, if a class have at least one abstract method, then the class must be declared abstract.

If a class is declared abstract it cannot be instantiated.

To use an abstract class you have to inherit it from another class, provide implementations to the
abstract methods in it.

If you inherit an abstract class you have to provide implementations to all the abstract methods in
it.

Example
This section provides you an example of the abstract class to create an abstract class just
use the abstract keyword before the class keyword, in the class declaration .
/* File name : Employee.java */
public abstract class Employee
{
private String name;
private String address;
private int number;
public Employee(String name, String address, int number)

65

System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;

}
public double computePay()
{
System.out.println("Inside Employee computePay");
return 0.0;
}
public void mailCheck()
{
System.out.println("Mailing a check to " + this.name
+ " " + this.address);
}
public String toString()
{
return name + " " + address + " " + number;
}
public String getName()
{
return name;
}
public String getAddress()
{
return address;
}
public void setAddress(String newAddress)
{
address = newAddress;
}
public int getNumber()
{
return number;
}
}

You can observe that except abstract methods the Employee class is same as normal class in Java. The
class is now abstract, but it still has three fields, seven methods, and one constructor.
Now you can try to instantiate the Employee class as shown below:
/* File name : AbstractDemo.java */
public class AbstractDemo
{
public static void main(String [] args)
{
/* Following is not allowed and would raise error */
Employee e = new Employee("George W.", "Houston, TX", 43);
System.out.println("\n Call mailCheck using Employee reference--");
e.mailCheck();
}

When you compile the above class, it gives you the following error:
Employee.java:46: Employee is abstract; cannot be instantiated
Employee e = new Employee("George W.", "Houston, TX", 43);

66

1 error

Inheriting the Abstract Class:


We can inherit the properties of Employee class just like concrete class as shown below:
/* File name : Salary.java */
public class Salary extends Employee
{
private double salary; //Annual salary
public Salary(String name, String address, int number, double
salary)
{
super(name, address, number);
setSalary(salary);
}
public void mailCheck()
{
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to " + getName()
+ " with salary " + salary);
}
public double getSalary()
{
return salary;
}
public void setSalary(double newSalary)
{
if(newSalary >= 0.0)
{
salary = newSalary;
}
}
public double computePay()
{
System.out.println("Computing salary pay for " + getName());
return salary/52;
}
}

Here, you cannot instantiate the Employee class, but you can instantiate the Salary Class, and using this
instance you can access the all the three fields and seven methods of Employee class as shown below.
/* File name : AbstractDemo.java */
public class AbstractDemo
{
public static void main(String [] args)
{
Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();

System.out.println("\n Call mailCheck using Employee reference--");


e.mailCheck();

This produces the following result:


67

Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference -Within mailCheck of Salary class
ailing check to Mohd Mohtashim with salary 3600.0
Call mailCheck using Employee reference-Within mailCheck of Salary class
ailing check to John Adams with salary 2400.

Abstract Methods:
If you want a class to contain a particular method but you want the actual implementation of that method
to be determined by child classes, you can declare the method in the parent class as abstract.

abstract keyword is used to declare the method as abstract.

You have to place the abstract keyword before the method name in the method declaration.

An abstract method contains a method signature, but no method body.

Instead of curly braces an abstract method will have a semoi colon ( ; ) at the end.

Below given is an example of the abstract method.


public abstract class Employee
{
private String name;
private String address;
private int number;
public abstract double computePay();
}

//Remainder of class definition

Declaring a method as abstract has two consequences:

The class containing it must be declared as abstract.

Any class inheriting the current class must either override the abstract method or declare itself as
abstract.

Note: Eventually, a descendant class has to implement the abstract method; otherwise, you would have a
hierarchy of abstract classes that cannot be instantiated.
Suppose Salary class is inherits the Employee class, then it should implement the computePay() method
as shown below:
/* File name : Salary.java */
public class Salary extends Employee
{
private double salary; // Annual salary

68

public double computePay()


{
System.out.println("Computing salary pay for " + getName());
return salary/52;
}
//Remainder of class definition
}

Java - Encapsulation

Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance,
polymorphism, and abstraction.
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data
(methods) together as as single unit. In encapsulation the variables of a class will be hidden from other
classes, and can be accessed only through the methods of their current class, therefore it is also known as
data hiding.
To achieve encapsulation in Java

Declare the variables of a class as private.

Provide public setter and getter methods to modify and view the variables values.

Example:
Below given is an example that demonstrates how to achieve Encapsulation in Java:
/* File name : EncapTest.java */
public class EncapTest{
private String name;
private String idNum;
private int age;
public int getAge(){
return age;
}
public String getName(){
return name;
}
public String getIdNum(){
return idNum;
}
public void setAge( int newAge){
age = newAge;
}
public void setName(String newName){
name = newName;
}

69

public void setIdNum( String newId){


idNum = newId;
}
}

The public setXXX() and getXXX() methods are the access points of the instance variables of the
EncapTest class. Normally, these methods are referred as getters and setters. Therefore any class that
wants to access the variables should access them through these getters and setters.
The variables of the EncapTest class can be accessed as below::
/* File name : RunEncap.java */
public class RunEncap{
public static void main(String args[]){
EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");
}

System.out.print("Name : " + encap.getName() + " Age : " + encap.getAge());

This would produce the following result:


Name : James Age : 20

Benefits of Encapsulation:

The fields of a class can be made read-only or write-only.

A class can have total control over what is stored in its fields.

The users of a class do not know how the class stores its data. A class can change the data type of
a field and users of the class do not need to change any of their code.

Java - Interfaces

An interface is a reference type in Java, it is similar to class, it is a collection of abstract methods. A


class implements an interface, thereby inheriting the abstract methods of the interface.
Along with abstract methods an interface may also contain constants, default methods, static methods,
and nested types. Method bodies exist only for default methods and static methods.
Writing an interface is similar to writing a class. But a class describes the attributes and behaviours of an
object. And an interface contains behaviours that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface need to be
defined in the class.
An interface is similar to a class in the following ways:
70

An interface can contain any number of methods.

An interface is written in a file with a .java extension, with the name of the interface matching
the name of the file.

The byte code of an interface appears in a .class file.

Interfaces appear in packages, and their corresponding bytecode file must be in a directory
structure that matches the package name.

However, an interface is different from a class in several ways, including:

You cannot instantiate an interface.

An interface does not contain any constructors.

All of the methods in an interface are abstract.

An interface cannot contain instance fields. The only fields that can appear in an interface must
be declared both static and final.

An interface is not extended by a class; it is implemented by a class.

An interface can extend multiple interfaces.

Declaring Interfaces:
The interface keyword is used to declare an interface. Here is a simple example to declare an interface:

Example:
Below given is an example of an interface:
/* File name : NameOfInterface.java */
import java.lang.*;
//Any number of import statements
public interface NameOfInterface
{
//Any number of final, static fields
//Any number of abstract method declarations\
}

Interfaces have the following properties:

An interface is implicitly abstract. You do not need to use the abstract keyword while declaring
an interface.

Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.
71

Methods in an interface are implicitly public.

Example:
/* File name : Animal.java */
interface Animal {
public void eat();
public void travel();
}

Implementing Interfaces:
When a class implements an interface, you can think of the class as signing a contract, agreeing to
perform the specific behaviors of the interface. If a class does not perform all the behaviors of the
interface, the class must declare itself as abstract.
A class uses the implements keyword to implement an interface. The implements keyword appears in
the class declaration following the extends portion of the declaration.
/* File name : MammalInt.java */
public class MammalInt implements Animal{
public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels");
}
public int noOfLegs(){
return 0;
}
public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}

This would produce the following result:


ammal eats
ammal travels

When overriding methods defined in interfaces there are several rules to be followed:

Checked exceptions should not be declared on implementation methods other than the ones
declared by the interface method or subclasses of those declared by the interface method.

The signature of the interface method and the same return type or subtype should be maintained
when overriding the methods.

72

An implementation class itself can be abstract and if so interface methods need not be
implemented.

When implementation interfaces there are several rules:

A class can implement more than one interface at a time.

A class can extend only one class, but implement many interfaces.

An interface can extend another interface, similarly to the way that a class can extend another
class.

Extending Interfaces:
An interface can extend another interface, similarly to the way that a class can extend another class. The
extends keyword is used to extend an interface, and the child interface inherits the methods of the parent
interface.
The following Sports interface is extended by Hockey and Football interfaces.
//Filename: Sports.java
public interface Sports
{
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
//Filename: Football.java
public interface Football extends Sports
{
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
//Filename: Hockey.java
public interface Hockey extends Sports
{
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}

The Hockey interface has four methods, but it inherits two from Sports; thus, a class that implements
Hockey needs to implement all six methods. Similarly, a class that implements Football needs to define
the three methods from Football and the two methods from Sports.

Extending Multiple Interfaces:


A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not
classes, however, and an interface can extend more than one parent interface.
73

The extends keyword is used once, and the parent interfaces are declared in a comma-separated list.
For example, if the Hockey interface extended both Sports and Event, it would be declared as:
public interface Hockey extends Sports, Event

Tagging Interfaces:
The most common use of extending interfaces occurs when the parent interface does not contain any
methods. For example, the MouseListener interface in the java.awt.event package extended
java.util.EventListener, which is defined as:
package java.util;
public interface EventListener
{}

An interface with no methods in it is referred to as a tagging interface. There are two basic design
purposes of tagging interfaces:
Creates a common parent: As with the EventListener interface, which is extended by dozens of other
interfaces in the Java API, you can use a tagging interface to create a common parent among a group of
interfaces. For example, when an interface extends EventListener, the JVM knows that this particular
interface is going to be used in an event delegation scenario.
Adds a data type to a class: This situation is where the term tagging comes from. A class that
implements a tagging interface does not need to define any methods (since the interface does not have
any), but the class becomes an interface type through polymorphism.
Java - Packages

Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and
annotations ) providing access protection and name space management.
Some of the existing packages in Java are::

java.lang - bundles the fundamental classes

java.io - classes for input , output functions are bundled in this package

Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a good
practice to group related classes implemented by you so that a programmer can easily determine that the
classes, interfaces, enumerations, annotations are related.

74

Since the package creates a new namespace there won't be any name conflicts with names in other
packages. Using packages, it is easier to provide access control and it is also easier to locate the related
classes.

Creating a package:
While creating a package, you should choose a name for the package and include a package statement
along with that name at the top of every source file that contains the classes, interfaces, enumerations,
and annotation types that you want to include in the package.
The package statement should be the first line in the source file. There can be only one package
statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation types will be
placed in the current default package.
To compile the Java programs with package statements you have to do use -d option as shown below.
javac -d Destination_folder file_name.java

Then a folder with the given package name is created in the specified destination, and the compiled class
files will be placed in that folder

Example:
Let us look at an example that creates a package called animals. It is a good practice to use names of
packages with lower case letters to avoid any conflicts with the names of classes, interfaces.
Below given package example contains interface named animals:
/* File name : Animal.java */
package animals;
interface Animal {
public void eat();
public void travel();
}

Now, let us implement the above interface in the same package animals:
package animals;
/* File name : MammalInt.java */
public class MammalInt implements Animal{
public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels");
}
public int noOfLegs(){
return 0;

75

public static void main(String args[]){


MammalInt m = new MammalInt();
m.eat();
m.travel();
}

Now compile the java files as shown below:


$ javac -d . Animal.java
$ javac -d . MammalInt.java

Now a package/folder with the name animals will be created in the current directory and these class
files will be placed in it as shown below.

You can execute the class file with in the package and get the result as shown below.
$ java animals.MammalInt
ammal eats
ammal travels

The import Keyword:


If a class wants to use another class in the same package, the package name does not need to be used.
Classes in the same package find each other without any special syntax.

Example:
Here, a class named Boss is added to the payroll package that already contains Employee. The Boss can
then refer to the Employee class without using the payroll prefix, as demonstrated by the following Boss
class.
package payroll;

76

public class Boss


{
public void payEmployee(Employee e)
{
e.mailCheck();
}
}

What happens if the Employee class is not in the payroll package? The Boss class must then use one of
the following techniques for referring to a class in a different package.

The fully qualified name of the class can be used. For example:

payroll.Employee
The package

can be imported using the import keyword and the wild card (*). For example:

import payroll.*;
The class itself

can be imported using the import keyword. For example:

import payroll.Employee;

Note: A class file can contain any number of import statements. The import statements must appear after
the package statement and before the class declaration.

The Directory Structure of Packages:


Two major results occur when a class is placed in a package:

The name of the package becomes a part of the name of the class, as we just discussed in the
previous section.

The name of the package must match the directory structure where the corresponding bytecode
resides.

Here is simple way of managing your files in Java:


Put the source code for a class, interface, enumeration, or annotation type in a text file whose name is
the simple name of the type and whose extension is .java. For example:
// File Name :

Car.java

package vehicle;
public class Car {
// Class implementation.
}

Now, put the source file in a directory whose name reflects the name of the package to which the class
belongs:
....\vehicle\Car.java

Now, the qualified class name and pathname would be as below:


77

Class name -> vehicle.Car

Path name -> vehicle\Car.java (in windows)

In general, a company uses its reversed Internet domain name for its package names. Example: A
company's Internet domain name is apple.com, then all its package names would start with com.apple.
Each component of the package name corresponds to a subdirectory.
Example: The company had a com.apple.computers package that contained a Dell.java source file, it
would be contained in a series of subdirectories like this:
....\com\apple\computers\Dell.java

At the time of compilation, the compiler creates a different output file for each class, interface and
enumeration defined in it. The base name of the output file is the name of the type, and its extension is
.class
For example:
// File Name: Dell.java
package com.apple.computers;
public class Dell{
}
class Ups{
}

Now, compile this file as follows using -d option:


$javac -d . Dell.java

This would put compiled files as follows:


.\com\apple\computers\Dell.class
.\com\apple\computers\Ups.class

You can import all the classes or interfaces defined in \com\apple\computers\ as follows:
import com.apple.computers.*;

Like the .java source files, the compiled .class files should be in a series of directories that reflect the
package name. However, the path to the .class files does not have to be the same as the path to the .java
source files. You can arrange your source and class directories separately, as:
<path-one>\sources\com\apple\computers\Dell.java
<path-two>\classes\com\apple\computers\Dell.class

By doing this, it is possible to give the classes directory to other programmers without revealing your
sources. You also need to manage source and class files in this manner so that the compiler and the Java
Virtual Machine (JVM) can find all the types your program uses.

78

The full path to the classes directory, <path-two>\classes, is called the class path, and is set with the
CLASSPATH system variable. Both the compiler and the JVM construct the path to your .class files by
adding the package name to the class path.
Say <path-two>\classes is the class path, and the package name is com.apple.computers, then the
compiler and JVM will look for .class files in <path-two>\classes\com\apple\compters.
A class path may include several paths. Multiple paths should be separated by a semicolon (Windows) or
colon (Unix). By default, the compiler and the JVM search the current directory and the JAR file
containing the Java platform classes so that these directories are automatically in the class path.

Set CLASSPATH System Variable:


To display the current CLASSPATH variable, use the following commands in Windows and UNIX
(Bourne shell):

In Windows -> C:\> set CLASSPATH

In UNIX -> % echo $CLASSPATH

To delete the current contents of the CLASSPATH variable, use :

In Windows -> C:\> set CLASSPATH=

In UNIX -> % unset CLASSPATH; export CLASSPATH

To set the CLASSPATH variable:

In Windows -> set CLASSPATH=C:\users\jack\java\classes

In UNIX -> % CLASSPATH=/home/jack/java/classes; export CLASSPATH

What are packages?

A package is a collection of classes and interfaces. Each package has its own name and organizes its toplevel (that is, nonnested) classes and interfaces into a separate namespace, or name collection. Although
same-named classes and interfaces cannot appear in the same package, they can appear in different
packages because a separate namespace assigns to each package.
From an implementation perspective, equating a package with a directory proves helpful, as does
equating a package's classes and interfaces with a directory's classfiles. Keep in mind other approaches
such as the use of databasesto implementing packages, so do not get into the habit of always
equating packages with directories. But because many JVMs use directories to implement packages, this
article equates packages with directories. The Java 2 SDK organizes its vast collection of classes and
interfaces into a tree-like hierarchy of packages within packages, which is equivalent to directories
79

within directories. That hierarchy allows Sun Microsystems to easily distribute (and you to easily work
with) those classes and interfaces. Examples of Java's packages include:

java.lang: A collection of language-related classes, such as Object and String,


organized in the java package's lang subpackage

java.lang.ref: A collection of reference-related language classes, such as


SoftReference and ReferenceQueue, organized in the ref sub-subpackage of the java
package's lang subpackage

javax.swing: A collection of Swing-related component classes, such as JButton, and


interfaces, such as ButtonModel, organized in the javax package's swing subpackage

Period characters separate package names. For example, in javax.swing, a period character separates
package name javax from subpackage name swing. A period character is the platform-independent
equivalent of forward slash characters (/), backslash characters (\), or other characters to separate
directory names in a directory-based package implementation, database branches in a hierarchical
database-based package implementation, and so on.
Tip
Just as you cannot store both a file and a directory with identical names in the same
directory, you cannot store a class or interface and a package with identical names in the
same package. For example, given a package named accounts, you cannot store both a
package and a class named payable in accounts. To avoid conflicting names, uppercase
the first letter of class and interface names, and lowercase the first letter of package
names. Using the previous example, store class Payable in package accounts as
accounts.Payable and package payable in package accounts as accounts.payable. Learn
more about this and other naming conventions from Sun's Code Conventions for the Java
Programming Language.
Create a package of classes and interfaces

Every source file's classes and interfaces organize into a package. In the package directive's absence,
those classes and interfaces belong to the unnamed package (the directory the JVM regards as the
current directorythe directory where a Java program begins its execution via the Windows java.exe,
or OS-equivalent, programand contains no subpackages). But if the package directive appears in a
source file, that directive names the package for those classes and interfaces. Use the following syntax to
specify a package directive in source code:
'package' packageName [ '.' subpackageName ... ] ';'
A package directive begins with the package keyword. An identifier

that names a package,


packageName, immediately follows. If classes and interfaces are to appear in a subpackage (at some
level) within packageName, one or more period-separated subpackageName identifiers appear after
packageName. The following code fragment presents a pair of package directives:
80

package game;
package game.devices;
The first package directive identifies

a package named game. All classes and interfaces appearing in that


directive's source file organize in the game package. The second package directive identifies a
subpackage named devices, which resides in a package named game. All classes and interfaces
appearing in that directive's source file organize in the game package's devices subpackage. If a JVM
implementation maps package names to directory names, game.devices maps to a game\devices
directory hierarchy under Windows and a game/devices directory hierarchy under Linux or Solaris.
Caution
Only one package directive can appear in a source file. Furthermore, the package directive
must be the first code (apart from comments) in that file. Violating either rule causes
Java's compiler to report an error.

To help you get comfortable with packages, I've prepared an example that spans all topics in this article.
In this section, you learn how to create the example's package. In later sections, you will learn how to
import a class and an interface from this package, how to move this package to another location on your
hard drive and still access the package from a program, and how to store the package in a jar file. Listing
1 presents the package's source code:
Listing 1. A.java
// A.java
package testpkg;
public class A
{
int x = 1;
public int y = 2;
protected int z = 3;
int returnx ()
{
return x;
}
public int returny ()
{
return y;
}
protected int returnz ()
{
return z;
}
public interface StartStop
{
void start ();
void stop ();
}
}
class B
{
public static void hello ()
{

81

System.out.println ("hello");

Listing 1 introduces the source code to your first named package. The package testpkg; directive
names that package testpkg. Within testpkg are classes A and B. Within A are three field declarations,
three method declarations, and an inner interface declaration. Within B is a single method declaration.
The entire source code stores in A.java because A is a public class. Our task: Turn this source code into
a package that consists of two classes and an inner interface (or a directory that contains three classfiles).
The following Windows-specific steps accomplish that task:
1. Open a Windows command window and ensure you are in the c: drive's root
directory (the main directoryrepresented by an initial backslash ( \) character). To
do that, type the c: command followed by the cd \ command. (If you use a different
drive, replace c: with your chosen drive. Also, do not forget to press the Enter key
after typing a command.)
2. Create a testpkg directory by typing md testpkg. Note: When following this article's
steps, do not type periods after the commands.
3. Make testpkg the current directory by typing cd testpkg.
4. Use an editor to enter Listing 1's source code and save that code to an A.java file in
testpkg.
5. Compile A.java by typing javac A.java. You should see classfiles A$StartStop.class,
A.class, and B.class appear in the testpkg directory.

Figure 1 illustrates Steps 3 through 5.

82

Figure 1. The testpkg


directory with its three classfiles equates to a testpkg package with classes A and B, and
A's inner interface StartStop

Congratulations! You have just created your first package. Think of this package as containing two
classes (A and B) and A's single inner interface (StartStop). You can also think of this package as a
directory containing three classfiles: A$StartStop.class, A.class, and B.class.
Note
To minimize package name conflicts (especially among commercial packages), Sun has
established a convention in which a company's Internet domain name reverses and
prefixes a package name. For example, a company with x.com as its Internet domain
name and a.b as a package name (a) followed by a subpackage name (b) prefixes com.x
to a.b, resulting in com.x.a.b. My article does not follow this convention because the
testpkg package is a throw-away designed for teaching purposes only.
Import a package's classes and interfaces

Once you have a package, you will want to import classes and/or interfacesactually, class and/or
interface namesfrom that package to your program, so it can use those classes and/or interfaces. One
way to accomplish that task is to supply the fully qualified package name (the package name and all

83

subpackage names) in each place where the reference type name (the class or interface name) appears,
as Listing 2 demonstrates:
Listing 2. Usetestpkg1.java
// Usetestpkg1.java
class Usetestpkg1 implements testpkg.A.StartStop
{
public static void main (String [] args)
{
testpkg.A a = new testpkg.A ();
System.out.println (a.y);
System.out.println (a.returny ());
Usetestpkg1 utp = new Usetestpkg1 ();
utp.start ();
utp.stop ();
}
public void start ()
{
System.out.println ("Start");
}
public void stop ()
{
System.out.println ("Stop");
}
}
By prefixing testpkg. to A, Usetestpkg1 accesses testpkg's

class A in two places and A's inner


interface StartStop in one place. Complete the following steps to compile and run Usetestpkg1:
1. Open a Windows command window and make sure you are in the c: drive's root
directory.
2. Ensure the classpath environment variable does not exist by executing set
classpath=. (I discuss classpath later in this article.)
3. Use an editor to enter Listing 2's source code and save that code to a
Usetestpkg1.java file in the root directory.
4. Compile Usetestpkg1.java by typing javac Usetestpkg1.java. You should see
classfile Usetestpkg1.class appear in the root directory.
5. Type java Usetestpkg1 to run this program.

Figure 2 illustrates Steps 3 through 5 and shows the program's output.

84

Figure 2. The root


directory contains Usetestpkg1.class and the testpkg directory that corresponds to the
testpkg package

According to Usetestpkg1's output, the main() method's thread successfully accesses testpkg.A's y
field and calls the returny() method. Furthermore, the output shows a successful implementation of the
testpkg.A.StartStop inner interface.
For Usetestpkg1, prefixing testpkg. to A in three places doesn't seem a big deal. But who wants to
specify a fully qualified package name prefix in a hundred places? Fortunately, Java supplies the import
directive to import a package's public reference type name(s), so you do not have to enter fully qualified
package name prefixes. Express an import directive in source code via the following syntax:
'import' packageName [ '.' subpackageName ... ] '.' ( referencetypeName | '*' ) ';'
An import directive consists of the import keyword immediately followed by an identifier that names a

package, packageName. An optional list of subpackageName identifiers follows to identify the


85

appropriate subpackage (if necessary). The directive concludes with either a referencetypeName
identifier that identifies a specific class or interface from the package, or an asterisk (*) character. If
referencetypeName appears, the directive is a single-type import directive. If an asterisk character
appears, the directive is a type-on-demand import directive.
Caution
As with the package directive, import directives must appear before any other code, with
three exceptions: a package directive, other import directives, or comments.

The single-type import directive imports the name of a single public reference type from a package, as
the following code fragment demonstrates:
import java.util.Date;
The previous single-type import

directive imports class name Date into source code. As a result, you
specify Date instead of java.util.Date in each place that class name appears in source code. For
example, when creating a Date object, specify Date d = new Date (); instead of java.util.Date d
= new java.util.Date ();.
Exercise care with single-type import directives. If the compiler detects a single-type import directive
that specifies a reference type name also declared in a source file, the compiler reports an error, as the
following code fragment demonstrates:
import java.util.Date;
class Date {}

The compiler regards the code fragment as an attempt to introduce two reference types with the same
Date name:
1. The imported Date reference type name from java's util subpackage via the singletype import directive
2. The Date class declaration

If the compiler permitted the above code fragment to compile, which Date reference type would the
compiler refer to upon encountering Date d = new Date ();?
Caution
A single-type import directive that imports a reference type name also declared in a
source file causes the compiler to report an error.

In contrast to a single-type import directive, a type-on-demand import directive imports public


reference type names from a package on an as-needed basis, as the following code fragment
demonstrates:
86

import java.net.*;

According to the code fragment above, if Socket or another java.net reference type name appears in a
source file, that name can appear without a java.net prefix. During compilation, when the compiler
detects Socket, it searches java.net to verify that Socket is a member of java's net subpackage. Once
verified, the compiler stores java.net with Socket in the classfile.
As with the single-type import directive, the type-on-demand import directive has problems. Consider
the following code fragment:
import a.*;
import b.*;
X x = new X ();

Suppose packages a and b each contain an X class. When the compiler determines that X is present in a
and b, the compiler reports an error because each package might have a different X implementation, and
the compiler has no way of knowing which X to import. To solve the problem, the developer must prefix
each occurrence of X with the fully qualified package name. For the code fragment above, this leads to
either a.X x = new a.X (); or b.X x = new b.X ();.
Caution
The compiler reports an error upon encountering a reference type name and two or more
type-on-demand import directives whose packages include that type name.

You can use a type-on-demand import directive to save yourself the trouble of specifying testpkg.,
wherever A appears in Usetestpkg1, as shown in Listing 3:
Listing 3. Usetestpkg2.java
// Usetestpkg2.java
import testpkg.*;
class Usetestpkg2 implements A.StartStop
{
public static void main (String [] args)
{
A a = new A ();
// Following code does not compile because
// testpkg.A
// System.out.println (a.x);
// Following code does not compile because
// outside testpkg.A
// System.out.println (a.returnx ());
System.out.println (a.y);
System.out.println (a.returny ());
// Following code does not compile because
// in testpkg.A
// System.out.println (a.z);
// Following code does not compile because
// access in testpkg.A
// System.out.println (a.returnz ());
SubA sa = new SubA ();
System.out.println (sa.returnZ ());

87

x is not public outside


returnx() is not public

z has protected access


returnz() has protected

// Following code does not compile because testpkg.B is not public


// in testpkg and hello() is not defined in a public class
// B.hello ();
Usetestpkg2 utp = new Usetestpkg2 ();
utp.start ();
utp.stop ();
}
public void start ()
{
System.out.println ("Start");
}
public void stop ()
{
System.out.println ("Stop");
}

}
class SubA extends A
{
int returnZ ()
{
// It is legal (regardless of package) for a subclass method to
// call a superclass's protected method
return super.returnz ();
}
}
Usetestpkg2's type-on-demand import directive imports reference type names A and A.StartStop

from testpkg. What about class B? We can't import that class name because B is not a public class
within testpkg. As a result, only code within testpkg's class A (and any other class you subsequently
add to that package) can access B.
Caution
Any attempt to import nonpublic classes or interfaces from a package causes the
compiler to report an error.

demonstrates that you can subclass a package's public class (A) and access that class's
protected members (such as int returnz()). To prove that, compile Usetestpkg2 (which you place in
the same directory as Usetestpkg1) and run the program. If successful, you see the following output:
Usetestpkg2

2
2
3
Start
Stop
3 is the

value of testpkg.A's protected z field, which testpkg.A's protected returnz() method returns
(via SubA's int returnZ() method).
Unlike returnz(), you cannot call int returnx() because the absence of an access modifier keyword
(private, public, or protected) implies package accessand a field or method with package access
is only accessible or callable from code within its class's (or interface's) package.

88

Note
Some reference types, such as Object and String, are located in java.lang. Because
programs frequently access java.lang's reference types, the compiler implicitly imports
all reference type names on an as-needed basis from java's lang subpackage. As a result,
you don't need to specify import java.lang.*; (although you can do so, if desired).
Move packages on the hard drive

For organizational purposes, you occasionally move package directories from place to place on the hard
drive. Accomplishing that task requires an understanding of how the classloader locates package
directories and classfiles at runtime. To allow the classloader to find package directories and classfiles,
the compiler places into a classfile fully qualified package name information for all reference type
names appearing in the source file that have declarations existing in a package other than the source
file's package. But that information helps with only part of the search. The rest of the search depends on
the presence or absence of the classpath environment variable.
Operating systems like Windows, Linux, and Solaris maintain environment variablesnamed entities
that let you configure different aspects of an operating system. Java recognizes one environment variable
that helps the classloader locate package directories and classfiles at runtime: classpath. If classpath
exists, the classloader focuses on classpath's list of directory paths. The search begins with the
leftmost directory path and continues to the rightmost directory path until either a directory path is found
that contains the searched-for classfile name (or package directory name) or the classloader throws a
NoClassDefFoundError object. For example, in Usetestpkg1 and Usetestpkg2, suppose you move
the testpkg directory from the root directory to a packages directory just below the root directory.
Assuming the Usetestpkg1.class, Usetestpkg2.class, and SubA.class classfiles exist in the root
directory, and assuming classpath is not set, attempts to execute java Usetestpkg1 or java
Usetestpkg2 from the root directory result in NoClassDefFoundErrorsbecause the classloader
cannot find testpkg in the root directory. To solve that problem, set classpath to both the current
directory (the root directory, in this example) and the packages directory as follows: set
classpath=.;\packages (under Windows) or setenv classpath .:/packages (under Solaris via the
csh shell program).
Note
You should include the current directory, via a period character, in the classpath
environment variable so the classloader will locate a program's starting classfile (such as
Usetestpkg2.class) and other classfiles (such as SubA.class) that exist in the unnamed
package.

When classpath is absent, the classloader limits its search to the current directory. As the classloader
encounters a reference type name in a loaded classfile, the classloader searches the current directory for
either a classfile name (if no fully qualified package name appears in the reference type name) that
matches the reference type name or a directory whose name matches the first identifier in a fully
89

qualified package name. For example, in Usetestpkg1, assume no classpath environment variable
exists and that the root directory is the current directory when you execute java Usetestpkg1. Upon
encountering testpkg, the classloader searches the root directory for a testpkg directory. If found, the
classloader searches testpkg for classfiles A$StartStop.class and A.class. If the classloader cannot
find either testpkg or one of the classfiles, the classloader throws a NoClassDefFoundError object and
the java.exe (or equivalent) program terminates. Otherwise, the classloader loads the classfiles.
Note
If a fully qualified package name includes a subpackage name, the classloader searches
the first package identifier's matching directory for a directory whose name matches the
second package identifier. For example, in a.b, the classloader searches directory a for
directory b. This process continues until all directories corresponding to package
identifiers have been found. After that, the classloader searches the final directory for a
classfile.
Jar files and packages

In addition to directory paths, classpath optionally identifies Java Archive files (jar files, or JARs) that
house packages. A jar file is a zip file with a .jar file extension, instead of a .zip file extension.
Jar files conveniently distribute packages; a developer needs to only distribute a single jar file instead of
a package's multiple files. Furthermore, a developer does not need to decipher how to recreate a
package's directory hierarchy because a jar file internally contains that hierarchy. Finally, compressed jar
files reduce less storage space and speeds transmission over a network compared to equivalent non-JARbased packages. Sun recognizes these advantages and distributes its set of standard packages in a single
rt.jar (runtime) jar file.
Let's convert the earlier testpkg package into a jar file. The following steps assume a testpkg
directory in the root directory, and A$StartStop.class, A.class, and B.class classfiles in testpkg:
1. Open a Windows command window and make sure you are in the c: drive's root
directory.
2. Ensure the classpath environment variable does not exist by executing set
classpath=.

3. Copy the following text into a file named manifest and store this file in the root directory:
4.
5.
6.
7.
8.

Specification-Title: testPkg specification title


Specification-Vendor: me
Specification-Version: 1.0
Implementation-Title: testPkg implementation title
Implementation-Vendor: you
Implementation-Version: 1.0.1

90

9. Execute jar cfm testpkg.jar manifest testpkg. If successful, you should see
testpkg.jar appear in the root directory.
10.Once testpkg.jar appears, execute deltree testpkg to delete the testpkg directory.

The previous steps introduce the following concepts:


1. Sun's SDK includes a jar program that creates and manages jar files. A list of
options follows jar on the command line. The cfm options are interpreted as follows:
c creates a jar file, f identifies the jar file as testpkg.jar, and m identifies manifest
as the file containing manifest information. Following cfm are the names of the jar
file, the manifest file, and the package directoryin the same order as the options
specify.
2. A manifest file stores metadata, data that describes a jar file's contents, in a jar file.
In our example, that metadata consists of Specification-Title, SpecificationVendor, Specification-Version, Implementation-Title, Implementation-Vendor, and
Implementation-Version.

Now that you have a testpkg.jar file, how do you reference that file so you can run Usetestpkg1 and
Usetestpkg2? Include testpkg.jar and the current directory in your classpath environment variable
by executing set classpath=testpkg.jar;. (or the platform-equivalent). Then execute java
Usetestpkg1 and Usetestpkg2. You should see the same output as you saw earlier in this article.
Package information

I created a manifest file in the previous section to introduce you to the java.lang.Package class. That
class allows you to obtain specification and implementation title, vendor, and version strings from a
package. Specification refers to a plan to which a package's classes and interfaces conform. In contrast,
implementation refers to a level of specification conformance. In both cases, the version string consists
of period-separated positive integers, similar to the Dewey decimal system (for example, 1.6.3, 2.5).
Specification and implementation strings prove useful in reporting package problems. Furthermore, the
implementation version string is useful in programmatically determining if a package's correct version
has been installed. To give you a taste of Package, I wrote an application that retrieves and displays a
package's specification and implementation strings:
// PkgInfo.java
class PkgInfo
{
public static void main (String [] args)
{
if (args.length < 1 || args.length > 2)
{
System.err.println ("usage: java PkgInfo pkgname [clsintname]");
return;
}
if (args.length == 2)
try
{
Class.forName (args [1]);
}

91

catch (ClassNotFoundException e)
{
System.err.println (args [1] + " not found.");
return;
}
Package p = Package.getPackage (args [0]);
if (p == null)
{
System.err.println (args [0] + " package not found.");
return;
}
System.out.println ("Name = " + p.getName ());
System.out.println ("Specification title = " +
p.getSpecificationTitle ());
System.out.println ("Specification vendor = " +
p.getSpecificationVendor ());
System.out.println ("Specification version = " +
p.getSpecificationVersion ());
System.out.println ("Implementation title = " +
p.getImplementationTitle ());
System.out.println ("Implementation vendor = " +
p.getImplementationVendor ());
System.out.println ("Implementation version = " +
p.getImplementationVersion ());
}
}
PkgInfo

requires one or two command-line arguments. The first command-line argument identifies a
package: PkgInfo calls Package's static Package getPackage(String name) method with the first
command-line argument to return a reference to a Package object corresponding to that argument. If no
package information is available, that is, if getPackage(String name)'s caller's classloader did not
load any classfiles corresponding to the package's classes and interfaces, that method returns null instead
of a Package reference.
The second command-line argument identifies one of the first command-line argument's classes or
interfaces, and proves necessary to ensure at least one classfile loads (via Class.forName (args
[1]);) before a call is made to getPackage(String name). If that is not done, most likely no package
information will be available for the package identified by the first command-line argument.
If only the first command-line argument is present, PkgInfo assumes you want information on a
package where one of the package's classfiles loads when the JVM starts running. One such package is
java.lang. If you were to execute java PkgInfo java.lang, you would see the following
specification and implementation strings for that package:
Name = java.lang
Specification title = Java Platform API Specification
Specification vendor = Sun Microsystems, Inc.
Specification version = 1.4
Implementation title = Java Runtime Environment
Implementation vendor = Sun Microsystems, Inc.
Implementation version = 1.4.0
The first line displays the package's name, which Package's String getName()

method returns. The


remaining lines display strings returned from Package's String getSpecificationTitle(), String
92

getSpecificationVendor(), String getSpecificationVersion(), String


getImplementationTitle(), String getImplementationVendor(),
getImplementationVersion()

and String

methods, respectively.

Let's display the specification and implementation strings in the previously created testpkg.jar
package file. To do that, execute java PkgInfo testpkg testpkg.A. If successful, you should see the
following output:
Name = testpkg
Specification title = testPkg specification title
Specification vendor = me
Specification version = 1.0
Implementation title = testPkg implementation title
Implementation vendor = you
Implementation version = 1.0.1

Look familiar? The specification and implementation strings first appeared in our testpkg.jar file's
manifest file. If you do not see this output but receive an error message, set the classpath environment
variable to both testpkg.jar and the current directory (set classpath=testpkg.jar;.), and ensure
the current directory is the root directory. That way, PkgInfo's classloader can locate testpkg.jar and
that package's class A.
Review

This article explored packages, a concept that saves you from reinventing the wheel. Packages help you
organize your classes and interfaces, which you can then import into your programs to save you from
rewriting code. For further organizational purposes, you can move these directories around on your hard
drive with the help of the classpath environment variable. Also, bundling a package's classfiles and
manifest information into a jar file simplifies package distribution.
I encourage you to email me with any questions you might have involving either this or any previous
article's material. (Please keep such questions relevant to material discussed in this column's articles.)
Your questions and my answers will appear in the relevant study guides.
In next month's article, I will introduce you to the Character, String, StringBuffer, and
StringTokenizer classes.
Jeff Friesen has been involved with computers for the past 20 years. He holds a degree in
computer science and has worked with many computer languages. Jeff has also taught
introductory Java programming at the college level. In addition to writing for JavaWorld, he
has written his own Java book for beginners Java 2 by Example, Second Edition (Que
Publishing, 2001; ISBN: 0789725932)and helped write Using Java 2 Platform, Special
Edition (Que Publishing, 2001; ISBN: 0789724685). Jeff goes by the nickname Java Jeff (or
JavaJeff). To see what he's working on, check out his Website at http://www.javajeff.com.

93

Learn more about this topic

Download this article's source code and resource files


http://images.techhive.com/downloads/idge/imported/article/jvw/2002/09/jw-0906java101.zip

For a glossary specific to this article, homework, and more, see the Java 101 study
guide that accompanies this article
http://www.javaworld.com/javaworld/jw-09-2002/jw-0906-java101guide.html

Sun's The Java Tutorial, Mary Campione, Kathy Walrath, Alison Huml (AddisonWesley, 2000; ISBN0201703939) provides a lesson on packages
http://java.sun.com/docs/books/tutorial/java/interpack/packages.html

Sun's Code Conventions for the Java Programming Language


http://java.sun.com/docs/codeconv/

For more information on jar files, read the following JavaWorld articles

"Java Tip 127See JAR Run," Shawn Silverman (May 2002)

"Java Tip 120Execute Self-Extracting JARs," Z. Steve Jin and John D. Mitchell
(November 2001)

Read Jeff's previous Java 101 column"Achieve Strong Performance with Threads,
Part 4" (JavaWorld, August 2002)
http://www.javaworld.com/javaworld/jw-08-2002/jw-0802-java101.html

Go on to Jeff's next column"Java's Character and Assorted String Classes Support


Text-Processing" (JavaWorld, October 2002)
http://www.javaworld.com/javaworld/jw-10-2002/jw-1004-java101.html?

Check out past Java 101 articles


http://www.javaworld.com/javaworld/topicalindex/jw-ti-java101.html

Browse the Core Java section of JavaWorld's Topical Index


http://www.javaworld.com/channel_content/jw-core-index.shtml

Need some Java help? Visit our Java Beginner discussion


http://forums.idg.net/webx?50@@.ee6b804

Java experts answer your toughest Java questions in JavaWorld's Java Q&A column
http://www.javaworld.com/javaworld/javaqa/javaqa-index.html

For Tips 'N Tricks, see


http://www.javaworld.com/javaworld/javatips/jw-javatips.index.html

Sign up for JavaWorld's free weekly email newsletters


http://www.javaworld.com/subscribe
94

You'll find a wealth of IT-related articles from our sister publications at IDG.net

Javaworld.com
javaPOint.com
Java Package

A java package is a group of similar types of classes, interfaces and sub-packages.


Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.

Advantage of Java Package


1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.

95

Simple example of java package


The package keyword is used to create a package in java.
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4.

public static void main(String args[]){

5.
6.

System.out.println("Welcome to package");
}

7. }

How to compile java package


If you are not using any IDE, you need to follow the syntax given below:
1. javac -d directory javafilename

For example
1. javac -d . Simple.java

The -d switch specifies the destination where to put the generated class file. You can use any directory
name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the package
within the same directory, you can use . (dot).

How to run java package program


You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java


To Run: java mypack.Simple
Output:Welcome to package

The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.

How to access package from another package?


There are three ways to access the package from outside the package.
96

1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*

If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to the
current package.

Example of package that import the packagename.*


1. //save by A.java
2. package pack;
3. public class A{
4.

public void msg(){System.out.println("Hello");}

5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6.

public static void main(String args[]){

7.

A obj = new A();

8.

obj.msg();

9.

10.}
Output:Hello

2) Using packagename.classname

If you import package.classname then only declared class of this package will be accessible.
97

Example of package by import package.classname


1. //save by A.java
2.
3. package pack;
4. public class A{
5.

public void msg(){System.out.println("Hello");}

6. }
1. //save by B.java
2. package mypack;
3. import pack.A;
4.
5. class B{
6.

public static void main(String args[]){

7.

A obj = new A();

8.

obj.msg();

9.

10.}
Output:Hello

3) Using fully qualified name

If you use fully qualified name then only declared class of this package will be accessible. Now there is
no need to import. But you need to use fully qualified name every time when you are accessing the class
or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql packages
contain Date class.

Example of package by import fully qualified name


1. //save by A.java
98

2. package pack;
3. public class A{
4.

public void msg(){System.out.println("Hello");}

5. }
1. //save by B.java
2. package mypack;
3. class B{
4.

public static void main(String args[]){

5.

pack.A obj = new pack.A();//using fully qualified name

6.

obj.msg();

7.

8. }
Output:Hello

Note: If you import a package, subpackages will not be imported.

If you import a package, all the classes and interface of that package will be imported excluding the
classes and interfaces of the subpackages. Hence, you need to import the subpackage as well.

Note: Sequence of the program must be package then import then class.

99

Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the package
further.
Let's take an example, Sun Microsystem has definded a package named java that contains many classes
like System, String, Reader, Writer, Socket etc. These classes represent a particular group e.g. Reader
and Writer classes are for Input/Output operation, Socket and ServerSocket classes are for networking
etc and so on. So, Sun has subcategorized the java package into subpackages such as lang, net, io etc.
and put the Input/Output related classes in io package, Server and ServerSocket classes in net packages
and so on.
The standard of defining package is domain.company.package e.g.
com.javatpoint.bean or org.sssit.dao.
Example of Subpackage
1. package com.javatpoint.core;
2. class Simple{
3.
4.
5.

public static void main(String args[]){


System.out.println("Hello subpackage");
}

6. }
To Compile: javac -d . Simple.java
To Run: java com.javatpoint.core.Simple
Output:Hello subpackage

How to send the class file to another directory or drive?


There is a scenario, I want to put the class file of A.java source file in classes folder of c: drive. For
example:

100

1. //save as Simple.java
2. package mypack;
3. public class Simple{
4.

public static void main(String args[]){

5.
6.

System.out.println("Welcome to package");
}

7. }
To Compile:

e:\sources> javac -d c:\classes Simple.java


To Run:
To run this program from e:\source directory, you need to set classpath of the directory
where the class file resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple
Another way to run this program by -classpath switch of java:

The -classpath switch can be used with javac and java tool.
101

To run this program from e:\source directory, you can use -classpath switch of java that tells where to
look for class file. For example:
e:\sources> java -classpath c:\classes mypack.Simple
Output:Welcome to package

Ways to load the class files or jar files


There are two ways to load the class files temporary and permanent.

Temporary
o

By setting the classpath in the command prompt

By -classpath switch

Permanent
o

By setting the classpath in the environment variables

By creating the jar file, that contains all the class files, and copying the jar file
in the jre/lib/ext folder.

Rule: There can be only one public class in a java source file and it must be
saved by the public class name.
1. //save as C.java otherwise Compilte Time Error
2.
3. class A{}
4. class B{}
5. public class C{}

How to put two public classes in a package?


If you want to put two public classes in a package, have two java source files containing
one public class, but keep the package name same. For example:
1. //save as A.java
2.
102

3. package javatpoint;
4. public class A{}
1. //save as B.java
2.
3. package javatpoint;
4. public class B{}

What is static import feature of Java5?


Click Static Import feature of Java5.

103