Anda di halaman 1dari 250

New Features of JAVA SE 6.

1) Changes in I/O this is a new feature added in Java SE 6, which has the ability to read text
from a terminal without having it echo on the screen through java.io.Console.
2) Collections Framework Enhancement:
In Collection framework, we are able to improve the performance hashing function that is
used by java.util.HashMap. It provides some new Collection interfaces also.
3) Changes in jar and zip:
Jar and zip support has been enhanced in JDK 6. In this, two new compressed streams have
been added. These are java.util.zip.DeflaterInputStream and
java.util.zip.InflaterOutputStream.
4) Java Web Start enhancements in version 6
The cache format of Java Web Start and Plug-In has been fully changed. All dialogs have
been redesigned and consolidated between Java Web Start and Plug-In to be more user
friendly.

5) JMX API Enhancements


Enhancements has been made to the JMX API in Java SE 6 like: JMX API now completely
supports Generics, MXBeans have been added and much more?

6) Java Platform Debugger Architecture Enhancements

JVMDI has been deleted in JAVA SE 6 and JPDA has been added. Some new Methods are
included like Boolean canGetInstanceInfo () and much more?

7) Java SE 6 Monitoring and Management Enhancements?

API provided by JAVA SE allows you to monitor and manage the JVM in the package
java.lang.management. JAVA SE 6 includes some enhancement to this API.

8) New Package java.util.spi in JDK 6

A new package Java.util.spi has been included in JAVA SE 6.

Serialization Changes and Enhancements in JAVA SE Development Kit 6


the new method ObjectStreamClass.lookupAny now used to obtain an ObjectStreamClass
instance for a non-serializable Class.

JavaTM Virtual Machine Technology


DTrace support has include in Java SE 6 HotSpot VM. The hotspot provider makes available
probes that can be used to track the lifespan of the VM, thread start and stop events
JAVA SE 6 Latest Features;

AVA SE 6 has the new ability to read text from a terminal without echoing on the screen,
through new class java.io.Console.

Console c=System. Console ();

Before using the Console, you must retrieve the Console object by invoking System.console ().
This method returns the object if it is available. But if it returns NULL, then Console operations
are restricted, because the OS doesn’t support them or the program was executed in non-
interactive environment.

Through the read Password method, the Console object support secure password entry. This
method helps in two ways. First, it suppresses echoing, so the password is not visible on the
screen. Second, read Password returns a character array, not a String, so the password can be
overwritten, removing it from memory as soon as it is no longer needed.

Object Oriented Concepts in Java:


Java is an Object Oriented Language. As a language that has the Object Oriented feature Java
supports the following fundamental concepts:

 Polymorphism
 Inheritance
 Encapsulation
 Abstraction
 Classes
 Objects
 Instance
 Method
 Message Parsing

Abstraction:
abstraction is only giving essential details w/o any background information.This is achieved in
java by
1) Abstract Class and Interface //We don't know the function implementation of code until unless
at run time or we have a information about the class which implementing this Interface or
Extends this Abstract Class If we click on this method it directly take us to Interface method not
to Class which actually implementing this method.
2) Hiding information by access modifier only give access to required
3) Object - Nothing can be access by Object ref.

 Representing essential details and hiding background details


 we using login pages without knowing back ground code

Abstraction refers to the ability to make a class abstract in OOP. An abstract class is one that
cannot be instantiated. All other functionality of the class still exists, and its fields, methods, and
constructors are all accessed in the same manner. You just cannot create an instance of the
abstract class.

Data Encapsulation:
Encapsulation exposes data that should be protected."
"Encapsulation is used to avoid privacy leaks" encapsulation is that it keeps your code
maintainable..

 The main benefit of encapsulation is the ability to modify our implemented code without
breaking the code of others who use our code. With this feature Encapsulation gives
maintainability, flexibility and extensibility to our code. Encapsulation is one of the four
fundamental OOP concepts. The other three are inheritance, polymorphism, and
abstraction.

Encapsulation is the technique of making the fields in a class private and providing access to the
fields via public methods. If a field is declared private, it cannot be accessed by anyone outside
the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred
to as data hiding.

Encapsulation can be described as a protective barrier that prevents the code and data being
randomly accessed by other code defined outside the class. Access to the data and code is tightly
controlled by an interface.

The main benefit of encapsulation is the ability to modify our implemented code without
breaking the code of others who use our code. With this feature Encapsulation gives
maintainability, flexibility and extensibility to our code.

The public methods are the access points to this class.s fields from the outside java world.
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.

ll the data and implementation code for the object should be entirely hidden for it interface.
Meaning that its become private from change after coded and the idea is that we can create an
interface method in a class and as long as the interface remains consistent and interact with the
objects.

Polymorphism:
Polymorphism is an important Object oriented concept and widely used in Java and other
programming language. Polymorphism in java is supported along with other concept like
abstraction, encapsulation and inheritance. Bit on historical side polymorphism word comes from
ancient Greek where poly means many so polymorphic are something which can take many
form.
Which advice use of common interface instead of concrete implementation while writing code.
When we program for interface our code is capable of handling any new requirement or
enhancement arise in near future due to new implementation of our common interface. If we
don't use common interface and rely on concrete implementation, we always need to change and
duplicate most of our code to support new implementation. It’s not only java but other Its not
only java but other object oriented language like C++ also supports polymorphism and it comes
as fundamental along with encapsulation , abstraction and inheritance.

How Polymorphism supported in Java


Java has excellent support of polymorphism in terms of Inheritance, method overloading and
method overriding. Method overriding allows java to invoke method based on a particular object
at run-time instead of declared type while coding. To get hold of concept let's see an example of
polymorphism in java:

Class:
Java classes contain fields and methods. A

Java class is nothing but a template for object you are going to create or it’s a blue print by using
this we create an object. In simple word we can say it’s a specification or a pattern which we
define and every object we define will follow that pattern.

What does Java Class Consist

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

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

Template is: Class (name of the class) {

(Here define member of class)


}

What are members of Class?


When we create a class its totally incomplete without defining any member of this class same like we
can understand one family is incomplete if they have no members.

Field: field is nothing but the property of the class or object which we are going to create .for example
if we are creating a class called computer then they have property like model, mem_size, hd_size,
os_type etc

Method: method is nothing but the operation that an object can perform it define the behavior of
object how an object can interact with outside world .startMethod (), shutdownMethod ().

Access Level of members: Access level is nothing but where we can use that members of
the class.

Each field and method has an access level:

 private: accessible only in this class


 package or default: accessible only in this package
 protected: accessible only in this package and in all subclasses of this class
 public: accessible everywhere this class is available

Objects in Java:
Object: Objects have states and behaviors. Example: A dog has states-color, name, breed as well as
behaviors -wagging, barking, eating. An object is an instance of a class.

Let us now look deep into what are objects. If we consider the real-world we can find many
objects around us, Cars, Dogs, and Humans etc. All these objects have a state and behavior.

If we consider a dog then its state is. Name, breed, color, and the behavior are. Barking,
wagging, running

If you compare the software object with a real world object, they have very similar
characteristics.

Software objects also have a state and behavior. A software object's state is stored in fields and
behavior is shown via methods.
So in software development methods operate on the internal state of an object and the object-to-
object communication is done via methods.

Creating an Object:
As mentioned previously a class provides the blueprints for objects. So basically an object is
created from a class. In java the new key word is used to create new objects.

There are three steps when creating an object from a class:

 Declaration . A variable declaration with a variable name with an object type.


 Instantiation . The 'new' key word is used to create the object.
 Initialization . The 'new' keyword is followed by a call o a constructor. This call
initializes the new object.

Accessing Instance Variables and Methods:


Instance variables and methods are accessed via created objects. To access an instance variable
the fully qualified path should be as follows:

Message Parsing:
 When a thread sends a message (an object) to another thread.
 Used for thread communication and synchronization in environments where the threads
do not have shared memory Hence the threads cannot share semaphores or monitors and
cannot use shared variables to communicate. Message passing can still be used, of course,
in a shared memory platform.
 Messages are sent through a channel with an operation like send (channel, message) and
received from a channel with an operation like receive (channel, message). Messages can
be passed synchronously, meaning the sender blocks until the received does a receive and
the receiver blocks until the sender does a send. Since the sender and receiver are at
specific known points in their code at a known specific instant of time, synchronous
message passing is also called a simple rendezvous with a one-way flow of information
from the sender to the receiver. An example is a chess game agent. The agents can
process messages synchronously, since they'll be handshaking throughout the entire
game.
 In asynchronous message passing, the sender does not block. If there is not a receiver
waiting to receive the message, the message is queued or buffered. The receiver still
blocks if there is no queued or buffered message when a receive is executed.

Introduction to JAVA
Introduction to Internet:

 The Internet is a global network of networks.

 People and organizations connect into the Internet so they can


access its massive store of shared information.
 The Internet is an inherently participative medium. Anybody
can publish information or create new services.
 The Internet is a cooperative endeavor -- no organization is in
charge of the net.

How Big is The Internet:

 As of Jan. 2000, there were over 72 million hosts on the Internet.


 About 48% of the people in the United States and Canada have access to the Internet.
 About 5% of the world's population has access to the Internet.

How Do I Connect to the Internet?


 Computer
 Connection - Phone Line, Cable, DSL, Wireless, ...
 Modem
 Network Software - TCP/IP
 Application Software - Web Browser, Email, ...
 Internet Service Provider (ISP)
What Can I Do on the Internet?

 Send and receive email messages.


 Download free software with FTP (File Transfer Protocol).
 Post your opinion to a Usenet newsgroup.
 Yack it up on IRC (Internet Relay Chat).
 Surf the World Wide Web.
 And much, much more.
 There is no charge for most services.

What is the World Wide Web?

 The Web was invented in 1991 by Tim Berners-Lee, while consulting at CERN (European
Organization for Nuclear Research) in Switzerland.
 The Web is a distributed information system.
 The Web contains multimedia.
 Information in the Web is connected by hyperlinks.

Browsing the Web:

 A web page is a document on the


World Wide Web.
 A web browser is the computer
program you use to retrieve and view
web pages.
 The most popular browsers are
Microsoft Internet Explorer and
Netscape Navigator.
Serving the Web
 Web pages are stored in computers called web servers.
 Any organization can setup a web server.
 A web site is a collection of web pages.
 The starting point for a web site sometimes is called a home
page

Web Security

 Secure web pages use encryption to


protect from eavesdroppers.
 Secure web pages use https.
 The lock icon closes on a secure page.
 The privacy policy should tell you what
the recipient will do with that
information.

Finding Information

Web Directory Search Engine

Easier to use. More resources.

Good for general subject searches Good for searches where you can
or browsing. use specific keywords.
Role of Java in internet Programming:
Because java runs on the java virtual machine. Therefore, java applications can run on top of the
heterogeneous set of systems connected to the internet.

Occasionally you will see companies using it in 3-teir apps, but that is starting to change a lot.
Java Applets were a brief fad in the 90's but people moved away from them. You seldom see
them anymore, except in the occasional chat room. On the server side jsp is also not frequently
used, asp and php are both faster. php is just as portable, so java has really lost a lot of headway
there.

Source(s):
Java is not the same as Javascript. Javascript is a scripting language designed by sun and
netscape to be run by web browsers. Javascript was designed specifically for the web.
Java is an object oriented programming language designed by sun so people could write
programs that look and run like crap on any platform.

JAVA plays the vital role because.... there is minimum chance off almost just 0.1% that java
software can get virus.

It is a platform independent language and a java program me in windows can be executed in


LINUX...

Because it's platform independent.


You can develop a program on Windows, and it will run on Linux or other operating systems.

Any information transmitted over computer networks, or the Internet, is subject to interception.
Some of that information could be sensitive, such as credit card numbers and other personal data.
To make the Internet more useful in an enterprise setting and for e-commerce, applications must
protect their users' information, using encryption, authentication, and secure communications
protocols. The secure Hypertext Transfer Protocol (HTTPS), which is HTTP over the Secure
Sockets Layer (SSL), is already being used successfully for e-commerce applications.

The Java Secure Socket Extension (JSSE), which is a set of Java packages that enable secure
Internet communications, is a framework and 100% Pure Java implementation of the Secure
Socket Layer (SSL). These packages enable you ,the Java developer, to develop secure network
applications that feature the secure passage of data between a client and a server running any
application protocol, such as HTTP, FTP, Telnet, or NTTP, over TCP/IP.

The good news is that JSSE has been integrated into the Java 2 SDK, Standard Edition, version
1.4 (J2SE 1.4). This means if you have J2SE 1.4 installed, then you can build secure Internet
applications based on SSL without downloading any additional packages. This two-part series of
articles provides a hands-on tutorial explaining how to develop secure Internet applications for
today's and tomorrow's market. This article is concerned with the server-side and the next article
will be concerned with the client-side. This article starts by presenting a detailed overview of
SSL, then shows you how to:

 Use the JSSE APIs


 Integrate SSL into your existing client-server applications
 Develop a simple HTTP server
 Revise the HTTP server to handle HTTPS requests
 Generate your own certificates using the keytool delivered with J2SE
 Develop, configure, and run a secure HTTP server

Features of JAVA:
The concept of Write-once-run-anywhere (known as the Platform independent) is one of the important
key feature of java language that makes java as the most powerful language.

Platform Independent
The concept of Write-once-run-anywhere (known as the Platform independent) is one of the
important key feature of java language that makes java as the most powerful language. Not even
a single language is idle to this feature but java is more closer to this feature. The programs
written on one platform can run on any platform provided the platform must have the JVM.

Simple
There are various features that makes the java as a simple language. Programs are easy to write
and debug because java does not use the pointers explicitly. It is much harder to write the java
programs that can crash the system but we can not say about the other programming languages.
Java provides the bug free system due to the strong memory management. It also has the
automatic memory allocation and deallocation system.

Object Oriented
To be an Object Oriented language, any language must follow at least the four characteristics.

 Inheritance : It is the process of creating the new classes and using the behavior of the
existing classes by extending them just to reuse the existing code and adding the
additional features as needed.
 Encapsulation: : It is the mechanism of combining the information and providing the
abstraction.
 Polymorphism: : As the name suggest one name multiple form, Polymorphism is the
way of providing the different functionality by the
functions having the same name based on the signatures of the methods.
 Dynamic binding : Sometimes we don't have the knowledge of objects about their
specific types while writing our code. It is the way of providing the maximum
functionality to a program about the specific type at runtime.

As the languages like Objective C, C++ fulfills the above four characteristics yet they are not
fully object oriented languages because they are structured as well as object oriented languages.
But in case of java, it is a fully Object Oriented language because object is at the outer most
level of data structure in java. No stand alone methods, constants, and variables are there in java.
Everything in java is object even the primitive data types can also be converted into object by
using the wrapper class.

Robust
Java has the strong memory allocation and automatic garbage collection mechanism. It provides
the powerful exception handling and type checking mechanism as compare to other
programming languages. Compiler checks the program whether there any error and interpreter
checks any run time error and makes the system secure from crash. All of the above features
makes the java language robust.

Distributed
The widely used protocols like HTTP and FTP are developed in java. Internet programmers can
call functions on these protocols and can get access the files from any remote machine on the
internet rather than writing codes on their local system.

Portable
The feature Write-once-run-anywhere makes the java language portable provided that the system
must have interpreter for the JVM. Java also has the standard data size irrespective of operating
system or the processor. These features make the java as a portable language.

Dynamic
While executing the java program the user can get the required files dynamically from a local
drive or from a computer thousands of miles away from the user just by connecting with the
Internet.

Secure
Java does not use memory pointers explicitly. All the programs in java are run under an area
known as the sand box. Security manager determines the accessibility options of a class like
reading and writing a file to the local disk. Java uses the public key encryption system to allow
the java applications to transmit over the internet in the secure encrypted form. The byte code
Verifier checks the classes after loading.

Performance
Java uses native code usage, and lightweight process called threads. In the beginning
interpretation of byte code resulted the performance slow but the advance version of JVM uses
the adaptive and just in time compilation technique that improves the performance.

Multithreaded
As we all know several features of Java like Secure, Robust, Portable, dynamic etc; you will be
more delighted to know another feature of Java which is Multithreaded.
Java is also a multithreaded programming language. Multithreading means a single program
having different threads executing independently at the same time. Multiple threads execute
instructions according to the program code in a process or a program. Multithreading works the
similar way as multiple processes run on one computer.
Multithreading programming is a very interesting concept in Java. In multithreaded programs not
even a single thread disturbs the execution of other thread. Threads are obtained from the pool of
available ready to run threads and they run on the system CPUs. This is how Multithreading
works in Java which you will soon come to know in details in later chapters.

Interpreted
We all know that Java is an interpreted language as well. With an interpreted language such as
Java, programs run directly from the source code.
The interpreter program reads the source code and translates it on the fly into computations.
Thus, Java as an interpreted language depends on an interpreter program.
The versatility of being platform independent makes Java to outshine from other languages.
The source code to be written and distributed is platform independent.
Another advantage of Java as an interpreted language is its error debugging quality. Due to this
any error occurring in the program gets traced. This is how it is different to work with Java.

Architecture Neutral
The term architectural neutral seems to be weird, but yes Java is an architectural neutral language
as well. The growing popularity of networks makes developers think distributed. In the world of
network it is essential that the applications must be able to migrate easily to different computer
systems. Not only to computer systems but to a wide variety of hardware architecture and
Operating system architectures as well. The Java compiler does this by generating byte code
instructions, to be easily interpreted on any machine and to be easily translated into native
machine code on the fly. The compiler generates an architecture-neutral object file format to
enable a Java application to execute anywhere on the network and then the compiled code is
executed on many processors, given the presence of the Java runtime system. Hence Java was
designed to support applications on network. This feature of Java has thrived the programming
language.

Jdk 7 Features:

Null-safe Method invocation:


This is the greatest feature which is going to added in Java 7.NullPoniterException is one of the
most common exception encountered in Java programming.

When I searched “NullPointerException” in Google, it gave about 5,570,000 results! This proves
how pervasive the exception is and how much effort a developer has to put in writing java code
free from null pointer exception.

Suppose if java has a feature to keep us in safe zone from null pointer exception, how is it? It
happens.

Suppose we have a method to fetch postal code of a person’s address:

01 public String getPostcode(Person person)


02 {
03 if (person != null)
04 {
05 Address address = person.getAddress();
06 if (address != null)
07 {
08 return address.getPostcode();
09 }}
10 return null;
11 }

Now check the above syntax. We have done lots of if (null! = object) checks to avoid
NullPointerException.

1 public String getPostcode(Person person)


2{
3 return person?.getAddress()?.getPostcode();
4}

Null-ignore invocation is concerned with dealing with possible null values in calling one or
especially a chain of methods. Check the syntax?. while calling method on an object. This is
Null-safe operator in Java 7. Thus, you can avoid lots of if (null!= object) checks in Java 7.

Strings in Switch Statements:

Whenever i am working with switch-case i felt, if the case allowed the string as a case variable
we feel so comfort on that. Because the switch case allows only the primitive data types as
variable such as integer, char etc.

Whenever i working with the methods that returns status of the operations like succesful, failed
like that. At that time i need to convert that in to constants. Then only i can move on switch
statements.

But java 7 offers the Strings as case variables in Switch Statements, So we are free from the
conversion process.

Multi-Exception Catch:

Another awesome update is Multi-Exception Catch, that means a single catch can handle
multiple exceptions. The syntax is

1 try
2{
3 block of statments
4}
5 catch(Exception1|Exception2|Exception3...)
6{
7 block of statements.
8}

It save lot of spaces in the code.

Bracket Notation for Collections:

This feature refers to the ability to reference a particular item in a Collection with square
brackets similar to how Arrays are accessed. Collection is one of the key concepts in java.

But when i was a student, I feel so discomfort with collections because of its strutcture.Thats
some thing different from basic things in java.

But now its also be like a simple things like array etc. For ex, a Collection class we might
consider something similar to arrays.

Instead of:

1 Collection<String> c = new ArrayList();


2 c.add(“one”);
3 c.add(“two”);
4 c.add(“three”);
5 Use:
6 Collection<String> c = new ArrayList {“one”, “two”, “three” };

Thats all folks.If any important updates are missing don’t hesitate to add that as comment

New Features of JAVA SE 6.


1. Changes in I/O
This is a new feature added in Java SE 6, which has the ability to read text from a
terminal without having it echo on the screen through java.io.Console.

2. Collections Framework Enhancement


In Collection framework, we are able to improve the performance hashing function
that is used by java.util.HashMap. It provides some new Collection interfaces also.

3. Changes in jar and zip


Jar and zip support has been enhanced in JDK 6. In this, two new compressed streams
have been added. These are java.util.zip.DeflaterInputStream and
java.util.zip.InflaterOutputStream.

4. Java Web Start enhancements in version 6


The cache format of Java Web Start and Plug-In has been fully changed. All dialogs
have been redesigned and consolidated between Java Web Start and Plug-In to be
more user friendly.

5. JMX API Enhancements


Enhancements has been made to the JMX API in Java SE 6 like : JMX API now
completely supports Generics, MXBeans have been added and much more?

6. Java Platform Debugger Architecture Enhancements


JVMDI has been deleted in JAVA SE 6 and JPDA has been added. Some new
Methods are included like boolean boolean canGetInstanceInfo() and much more?

7. Java SE 6 Monitoring and Management Enhancements


API provided by JAVA SE allows you to monitor and manage the JVM in the
package java.lang.management. JAVA SE 6 includes some enhancement to this API.

8. New Package java.util.spi in JDK 6


A new package Java.util.spi has been included in JAVA SE 6.

9. Networking features and enhancements in Java SE version 6.0


This feature include enhancement in networkInterface, support for Internationalized
Domain Names, HTTP Negotiate Authentication and much more?

10. Enhancements in java.lang.Class and java.lang.reflect


Some new Methods are included in java.lang.Class like : getInterfaces(), getClasses(),
getConsturctors(), getMethod(String, Class?) and much more?.

11. Enhancement in RMI for JDKTM 6


java.rmi.MarshalledObject now support generics

12. JAVA SE 6 Security Enhancements


JAVA SE 6 has added support for some security functionality: the XML Digital
signature API and implementation, Smart Card I/O API. And much more?

13. Serialization Changes and Enhancements in JAVA SE Development Kit 6


The new method ObjectStreamClass.lookupAny now used to obtain an
ObjectStreamClass instance for a non-serializable Class

14. JavaTM Virtual Machine Technology


DTrace support has include in Java SE 6 HotSpot VM. The hotspot provider makes
available probes that can be used to track the lifespan of the VM, thread start and stop
events

15. Scripting for the Java Platform


By using this Features developers integrate Java technology and scripting languages
by defining a standard framework and application programming interface (API)
16. Leveraging Security in the Native Platform Using Java SE 6 Technology
The JAVA SE 6 provide a large set of security APIs. These Security APIs span a
wide range of areas, including cryptography public key infrastructure, secure
communication, authentication, and access control.
17. JAX-Web Services 2.0 With the Java SE 6 Platform
Most exciting new features of the JAVA SE 6 is support for the Java API for XML
Web Services (JAX-WS), version 2.0.

New Features in JDK 5


Here are the list of new Features added to the JDK 5.

1. Metadata

2. Auto-boxing and auto-unboxing of primitive type variables

3. Var-args

4. Formatted Output using The printf Method

5. Formatted Input

6. Concurrency utilities

7. Scanners

8. Static Imports

9. Enumerated Types

10. Generics

11. JVM Improvements

12. Enhanced for Loop

13. RMI compiler-rmic

14. Class-data sharing

15. Monitoring

16. JVM Profiling API (JVMTI)

17. Improved diagnostic capability


18. Desktop Client

19. Core XML support

20. Supplementary character support

21. JDBC rowsets

J2SE Version 1.4

Code named Merlin and released on February 6, 2002 (first release under JCP).

New features in J2SE 1.4

 XML Processing
 Java Print Service
 Logging API
 Java Web Start
 JDBC 3.0 API
 Assertions
 Preferences API
 Chained Exception
 IPv6 Support
 Regular Expressions
 Image I/O API

J2SE Version 1.3

Code named Kestrel and released on May 8, 2000.

New features in J2SE 1.3

 Java Sound
 Jar Indexing
 A huge list of enhancements in almost all the java area.

J2SE Version 1.2

Code named Playground and released on December 8, 1998.

New features in J2SE 1.2

 Collections framework.
 Java String memory map for constants.
 Just In Time (JIT) compiler.
 Jar Signer for signing Java ARchive (JAR) files.
 Policy Tool for granting access to system resources.
 Java Foundation Classes (JFC) which consists of Swing 1.0, Drag and Drop, and Java 2D class
libraries.
 Java Plug-in
 Scrollable result sets, BLOB, CLOB, batch update, user-defined types in JDBC.
 Audio support in Applets.

JDK Version 1.1

Released on February 19, 1997


New features in JDK 1.1

 JDBC (Java Database Connectivity)


 Inner Classes
 Java Beans
 RMI (Remote Method Invocation)
 Reflection (introspection only)

JDK Version 1.0

Codenamed Oak and released on January 23, 1996.

How To Create a Simple Java Programme:

Let's create a class createfirstprogram that will print a message "Welcome to RoseIndia.net"
on the console.

Here is the code of createfirstprogram.java file:

class createfirstprogram{
public static void main(String[] args) {
System.out.println("Welcome to RoseIndia.net");
}
}

Download this example.

Save this program in the specified directory ("C:\Vinod" in this example) with name
createfirstprogram.java.

This class contains public, static and void java keywords (these are pre-defined words in java
which carries specific meaning).
public keyword specifies the accessibility issues of a class. Here, It specifies that method can be
accessed from anywhere.
static keyword indicates that this method can be invoked simply by using the name of the class
without creating any class-object.
void keyword specifies that this method will not return any type of data.
main() method is the main entry point of the program, to start execution. First of all JVM calls
the main method of a class and start execution. JVM (Java Virtual Machine) is responsible for
running java programs.
args is a string array that takes values from java command line. Its index starts from '0'. We can
access values by writing args[0], args[1] etc.
println() function prints the output to the standard output stream (monitor).
out represents the standard output stream (monitor).

Now, you are ready to compile and run this program. Open the command prompt and go to the
directory ("C:\vinod" in this example) where your program is saved.

Java uses the "javac" command to compile your program (Type javac createfirstprogram.java)
. After compiling successfully, you can run it. Java uses the "java" command to execute your
program (Type java createfirstprogram). It will print "Welcome to RoseIndia.net".

Output of program:

C:\vinod>javac createfirstprogram.java

C:\vinod>java createfirstprogram
Welcome to RoseIndia.net

C:\vinod>_

DataTypes and ControlStructures of Java Working with Arrays:


Constructors in java
Constructors are used to assign initial values to instance variables of the class. A default
constructor with no arguments will be called automatically by the Java Virtual Machine (JVM).
Constructor is always called by new operator. Constructor is declared just like as we declare
methods, except that the constructor doesn’t have any return type. Constructor can be overloaded
provided they should have different arguments because JVM differentiates constructors on the
basis of arguments passed in the constructor. Whenever we assign the name of the method same
as class name. Remember this method should not have any return type. This is called as
constructor overloading. A constructor is a special method that is used to initialize a newly
created object and is called just after the memory is allocated for the object .It can be used to
initialize the objects ,to required ,or default values at the time of object creation.It is not
mandatory for the coder to write a constructor for the class.
If no user defined constructor is provided for a class, compiler initializes member variables to its
default values.
Numeric data types are set to 0
Char data types are set to null character (‘\0’)
Reference variables are set to null

A constructor is a special method that is used to initialize a newly created object and is
called just after the memory is allocated for the object

It can be used to initialize the objects ,to required ,or default values at the time of object
creation

It is not mandatory for the coder to write a constructor for the class

If no user defined constructor is provided for a class, compiler initializes member variables to
its default values.

 numeric data types are set to 0


 char data types are set to null character(‘\0’)
 reference variables are set to null

In order to create a Constructor observe the following rules

1) It has the same name as the class

2) It should not return a value not even void

Assignment 1: Create your First Constructor


Step 1: Type following code in your editor

01.class Demo{
02.int value1;
03.int value2;
04.Demo(){
05.value1 = 10;
06.value2 = 20;
07.System.out.println("Inside Constructor");
08.}
09.public void display(){
10.System.out.println("Value1 === "+value1);
11.System.out.println("Value2 === "+value2);
12.}
13.public static void main(String args[]){
14.Demo d1 = new Demo();
15.d1.display();
16.}
17.}

Step 2) Save , Run & Compile the code. Observe the output.

constructor overloading

Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors by taking
into account the number of parameters in the list and their type

Examples of valid constructors for class Account are

Account(int a);
Account (int a,int b);
Account (String a,int b);

Assignment 2:To understand Constructor Overloading

Step 1) Type the code in editor

01.class Demo{
02.int value1;
03.int value2;
04./*Demo(){
05.value1 = 10;
06.value2 = 20;
07.System.out.println("Inside 1st Constructor");
08.}*/
09.Demo(int a){
10.value1 = a;
11.System.out.println("Inside 2nd Constructor");
12.}
13.Demo(int a,int b){
14.value1 = a;
15.value2 = b;
16.System.out.println("Inside 3rd Constructor");
17.}
18.public void display(){
19.System.out.println("Value1 === "+value1);
20.System.out.println("Value2 === "+value2);
21.}
22.public static void main(String args[]){
23.Demo d1 = new Demo();
24.Demo d2 = new Demo(30);
25.Demo d3 = new Demo(30,40);
26.d1.display();
27.d2.display();
28.d3.display();
29.}
30.}

Step 2) Save , Compile & Run the Code.

Step 3) Error = ?. Try and debug the error before proceeding to next step.

Step 4) Every class has a default Constructor. Default Constructor for class Demo is Demo(). In
case you do not provide this constructor the compiler creates it for you and initializes the
variables to default values. You may choose to override this default constructor and initialize
variables to your desired values as shown in Assignment 1.

But if you specify a parametrized constructor like Demo(int a) ,and want to use the default
constructor Demo(), it is mandatory for you to specify it.

In other words, in case your Constructor is overridden , and you want to use the default
constructor , its need to be specified.

Step 4) Uncomment line # 4-8. Save , Compile & Run the code.
constructor chaining

Consider a scenario where a base class is extended by a child .

Whenever an object of the child class is created , the constructor of the parent class is invoked
first.

This is called Constructor chaining.

Assignment 3: To understand constructor chaining

Step1 ) Copy the following code in the editor

01.class Demo{
02.int value1;
03.int value2;
04.Demo(){
05.value1 = 1;
06.value2 = 2;
07.System.out.println("Inside 1st Parent Constructor");
08.}
09.Demo(int a){
10.value1 = a;
11.System.out.println("Inside 2nd Parent Constructor");
12.}
13.public void display(){
14.System.out.println("Value1 === "+value1);
15.System.out.println("Value2 === "+value2);
16.}
17.public static void main(String args[]){
18.DemoChild d1 = new DemoChild();
19.d1.display();
20.}
21.}
22.class DemoChild extends Demo{
23.int value3;
24.int value4;
25.DemoChild(){
26.//super(5);
27.value3 = 3;
28.value4 = 4;
29.System.out.println("Inside the Constructor of Child");
30.}
31.public void display(){
32.System.out.println("Value1 === "+value1);
33.System.out.println("Value2 === "+value2);
34.System.out.println("Value1 === "+value3);
35.System.out.println("Value2 === "+value4);
36.}
37.}

Step 2) Run the Code. Owing to constructor chaining , when object of child class DemoChild is
created , constructor Demo() of the parent class is invoked first and later constructor
DemoChild() of the child is created.

Expected Output =

Inside 1st Parent Constructor


Inside the Constructor of Child
Value1 === 1
Value2 === 2
Value1 === 3
Value2 === 4

Step3 ) You may observe the constructor of the parent class Demo is overridden . What is you
want to call the overridden constructor Demo(int a) instead of the default constructor Demo()
when your child object is created ???

In such cases you can use the keyword "super" to call overridden constructors of the parent
class.

Syntax:-

super();
--or--
super(parameter list);

Ex: If your constructor is like Demo(String Name,int a)

you will specify super("Java",5)


If used ,the keyword super needs to be the first line of code in the constructor of the child
class.

When you create a new instance (a new object) of a class using the new keyword, a constructor
for that class is called. Constructors are used to initialize the instance variables (fields) of an
object. Constructors are similar to methods, but with some important differences.

 Constructor name is class name. A constructors must have the same name as the class
its in.
 Default constructor. If you don't define a constructor for a class, a default parameterless
constructor is automatically created by the compiler. The default constructor calls the
default parent constructor (super()) and initializes all instance variables to default value
(zero for numeric types, null for object references, and false for booleans).
 Default constructor is created only if there are no constructors. If you define any
constructor for your class, no default constructor is automatically created.
 Differences between methods and constructors.
o There is no return type given in a constructor signature (header). The value is this
object itself so there is no need to indicate a return value.
o There is no return statement in the body of the constructor.
o The first line of a constructor must either be a call on another constructor in the
same class (using this), or a call on the superclass constructor (using super). If
the first line is neither of these, the compiler automatically inserts a call to the
parameterless super class constructor.

These differences in syntax between a constructor and method are sometimes hard to see
when looking at the source. It would have been better to have had a keyword to clearly
mark constructors as some languages do.

 this(...) - Calls another constructor in same class. Often a constructor with few
parameters will call a constructor with more parameters, giving default values for the
missing parameters. Use this to call other constructors in the same class.
 super(...). Use super to call a constructor in a parent class. Calling the constructor for
the superclass must be the first statement in the body of a constructor. If you are satisfied
with the default constructor in the superclass, there is no need to make a call to it because
it will be supplied automatically.

Method OverLoading:
In Java it is possible to define two or more methods within the same class that share the same
name, as long as their parameter declarations are different. When this is the case, the methods are
said to be overloaded, and the process is referred to as method overloading. Method overloading
is one of the ways that Java implements polymorphism.
If you have never used a language that allows the overloading of methods, then the concept may
seem strange at first. But as you will see, method overloading is one of Java's most exciting and
useful features. When an overloaded method is invoked, Java uses the type and/or number of
arguments as its guide to determine which version of the overloaded method to actually call.
Thus,
overloaded methods must differ in the type and/or number of their parameters. While overloaded
methods may have different return types, the return type alone is insufficient to distinguish two
versions of a method. When Java encounters a call to an overloaded method, it simply executes
the version of the method whose parameters match the arguments used in the call. Here is a
simple example that illustrates method overloading:

// Demonstrate method overloading.


class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.2);
System.out.println("Result of ob.test(123.2): " + result);
}
}

This program generates the following output:

No parameters
a: 10
a and b: 10 20
double a: 123.2
Result of ob.test(123.2): 15178.24

As you can see, test( ) is overloaded four times. The first version takes no parameters, the second
takes one integer parameter, the third takes two integer parameters, and the fourth takes one
double parameter. The fact that the fourth version of test( ) also returns a value is of no
consequence relative to overloading, since return types do not play a role in overload resolution.

When an overloaded method is called, Java looks for a match between the arguments used to call
the method and the method's parameters. However, this match need not always be exact. In some
cases Java's automatic type conversions can play a role in overload resolution. For example,
consider the following program:

Automatic Coversions in Method OverLoading:


/ Automatic type conversions apply to overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
void test(double a) {
System.out.println("Inside test(double) a: " + a);
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
int i = 88;
ob.test();
ob.test(10, 20);
ob.test(i); // this will invoke test(double)
ob.test(123.2); // this will invoke test(double)
}
}

This program generates the following output:

No parameters
a and b: 10 20
Inside test(double) a: 88
Inside test(double) a: 123.2

As you can see, this version of OverloadDemo does not define test(int). Therefore, when test( )
is called with an integer argument inside Overload, no matching method is found. However,
Java can automatically convert an integer into a double, and this conversion can be used to
resolve the call. Therefore, after test(int) is not found, Java elevates i to double and then calls
test(double). Of course, if test(int) had been defined, it would have been called instead. Java
will employ its automatic type conversions only if no exact match is found.

Method overloading supports polymorphism because it is one way that Java implements the "one
interface, multiple methods" paradigm. To understand how, consider the following. In languages
that do not support method overloading, each method must be given a unique name. However,
frequently you will want to implement essentially the same method for different types of data.
Consider the absolute value function. In languages that do not support overloading, there are
usually three or more versions of this function, each with a slightly different name. For instance,
in C, the function abs( )
returns the absolute value of an integer, labs( ) returns the absolute value of a long integer, and
fabs() returns the absolute value of a floating-point value. Since C does not support overloading,
each function has to have its own name, even though all three functions do essentially the same
thing. This makes the situation more complex, conceptually, than it actually is. Although the
underlying concept of each function is the same, you still have three names to remember. This
situation does not occur in Java, because each absolute value method can use the same name.
Indeed, Java's standard class library includes an absolute value method, called abs( ). This
method is overloaded
by Java's Math class to handle all numeric types. Java determines which version of abs() to call
based upon the type of argument.

The value of overloading is that it allows related methods to be accessed by use of a common
name. Thus, the name abs represents the general action which is being performed. It is left to the
compiler to choose the right specific version for a particular circumstance. You, the programmer,
need only remember the general operation being performed. Through the application of
polymorphism, several names have been reduced to one. Although this example is fairly simple,
if you expand the concept, you can see how overloading can help you manage greater
complexity.

When you overload a method, each version of that method can perform any activity you desire.
There is no rule stating that overloaded methods must relate to one another. However, from a
stylistic point of view, method overloading implies a relationship. Thus, while you can use the
same name to overload unrelated methods, you should not. For example, you could use the name
sqr to create methods that return the square of an integer and the square root of a floating-point
value. But these two operations are fundamentally different. Applying method overloading in
this manner defeats its original purpose. In practice, you should only overload closely related
operations.
Concept of This (this keyword):
Used to call the default constructor of the same class from the parameterized constructor of the
same class.
This (…):- used to call the parameterized constructor of the same class from default constructor
or other category constructor of the same class.
Whenever using the “this” keyword the statement must be the first statement must be the first
statement. Within an instance method or a constructor, this is a reference to the current object —
the object whose method or constructor is being called. You can refer to any member of the
current object from within an instance method or a constructor by using this. The keyword this is
useful when you need to refer to instance of the class from its method. The keyword helps us to
avoid name conflicts.
class This1
{
int a,b;
This1 (){
this(50,60);
a=10;
b=20;
System.out.println("a="+a);
System.out.println("b="+b);
}
This1(int a,int b)
{

this(11);
this.a=a;
this.b=b;
System.out.println("aa="+a);
System.out.println("bb="+b);
}
This1(int a)
{
this.a=a;
b=a;
System.out.println("a1="+a);
System.out.println("b1="+b);
}

}
Public class this
{
Public static void main (String arg[])
{
This1 e=new This1 ();

}
}

Concept of super :-
It is the reserve keyword which is use to differentiate the base class feature with derive class
features if and only if they are similar the base class feature will be practiced with super keyword
Super keyword plays an important role at three levels
1. at variable level
2. at method level
3. at constructor level

At variable level:-
To access base class data member into derive class. If and only if the derive class data member’s
and the base class data member are similar then the the base class data member keyword in the
context of data member.
Ex. Super base class data member;

lass Base1{
protected int num;
public Base1(int n){
num = n;
System.out.println(“\n\t1-parameter constructor of Base class.”);
}
public void display(){
System.out.println(“\n\tDisplay of Base class: ” + num);
}
}
class Derived1 extends Base1{
private int num;
public Derived1(int n1,int n2){
super(n1);
//super(n);
num = n2;
System.out.println(“\n\t1-parameter constructor of Derived class.”);
}
public void display(){
super.display ();
System.out.println (“\n\tDisplay of Derived class: ” + num);
}
}
public class UseOfSuper{
public static void main(String args[])
{
Derived1 ob = new Derived1 (10, 20);
ob.display ();
}
}
Result:
1-parameter constructor of Base class.
1-parameter constructor of Derived class.
Display of Base class: 10
Display of Derived class: 20

At method level:-
To access the base class member method into derive class and derive class method and base class
methods are similar than the base class methods will be called with respect to super keyword in
the context of derive class.

If your method overrides one of its superclass's methods, you can invoke the overridden method
through the use of the keyword super. You can also use super to refer to a hidden field (although
hiding fields is discouraged). Consider this class, Superclass:

Public class Superclass {

Public void printMethod () {


System.out.println ("Printed in Superclass.");
}
}

Here is a subclass, called Subclass that overrides printMethod ():

Public class Subclass extends Superclass {

// overrides printMethod in Superclass


Public void printMethod () {
super.printMethod ();
System.out.println ("Printed in Subclass");
}
Public static void main (String [] args) {
Subclass s = new Subclass ();
s.printMethod ();
}
}
Within Subclass, the simple name printMethod () refers to the one declared in Subclass, which
overrides the one in Superclass. So, to refer to printMethod () inherited from Superclass,
Subclass must use a qualified name, using super as shown. Compiling and executing Subclass
prints the following:

Printed in Superclass.
Printed in Subclass

At Constructor Level:-
It is used to call the default constructors of the immediate base class from drive class.
Super (---):-
It is used to call the parameterized constructors of the base class from the drive class.
Class Myclass
{
Public Myclass (int a, int b, int c)
{
System.out.println ("\n"+a+"\n"+b+"\n"+c);
}

}
class ourclass extends Myclass
{

Public ourclass (int l, int m, int n,int a,int b,int c)


{
super (a,b,c);
System.out.println ("\n"+l+"\n"+m+"\n"+n);

}
class ownclass extends ourclass
{

Public ownclass (int x, int y, int z, int l, int m, int n, int a, int b, int c)
{
super (l,m,n,a,b,c);
System.out.println ("\n"+x+"\n"+y+"\n"+z);
}
}
public class super1
{ public static void main(String args[])
{
ownclass o=new ownclass(1,2,3,4,5,6,7,8,9);
}
}
}

Garbage collection :
Since objects are dynamically allocated by using the new operator, you might be
wondering how such objects are destroyed and their memory released for later reallocation. In
some languages, such as C++, dynamically allocated objects must be manually released by use
of a delete operator.

Java takes a different approach; it handles deallocation for you automatically. The
technique that accomplishes this is called garbage collection. It works like this: when no
references to an object to an object exist, that object is assumed to be no longer needed, and the
memory occupied by the object can be reclaimed. There is no explicit need to destroy objects as
in C++. Garbage collection only occurs sporadically (if at all) during the execution of your
program. It will not occur simply because one or more objects exist that are no longer used.
Furthermore, different java run-time implementations will take varying approaches to garbage
collection, but for the most part, you should not have to think about it while writing your
programs

Code for Garbage Collection

In this section, you will learn how to force a garbage collector to work by creating many objects.

Description of program:

The following code of program will help you in forcing the garbage collection. First of all we
have created an object for the garbage collector to perform some operation. Then we have used
the System.gc (); method to force the garbage collection on that object. Then we have used the
System.currentTimeMillis (); method to show the time take by the garbage collector.

import java.util.Vector;

public class GarbageCollector{


public static void main(String[] args) {
int SIZE = 200;
StringBuffer s;
for (int i = 0; i < SIZE; i++) {
}
System.out.println("Garbage Collection started explicitly.");
long time = System.currentTimeMillis();
System.gc();
System.out.println("It took " + (System.currentTimeMillis()-
time) + " ms");
}
}

Output of the program:

C:\unique>javac
GarbageCollector.java

C:\unique>java GarbageCollector
Garbage Collection started explicitly.
It took 782 ms

Java program to perform garbage collection

This program performs garbage collection. Free memory in java virtual machine is printed and
then garbage collection is done using gc method of RunTime class, freeMemory method returns
amount of free memory in jvm, getRunTime method is used to get reference of current RunTime
object.

import java.util.*;

Class GarbageCollection
{
Public static void main (String s[]) throws Exception
{
Runtime rs = Runtime.getRuntime ();
System.out.println ("Free memory in jvm (Java Virtual Machine) before Garbage Collection
= "+rs.freeMemory ());
rs.gc();
System.out.println ("Free memory in jvm (Java Virtual Machine) after Garbage Collection =
"+rs.freeMemory ());
}
}

Output:
The finalize () Method

Sometimes an object will need to perform some action when it is destroyed. For example,
if an object is holding some non-java resource such as a file handle or window character font,
then you might want to make sure these resources are freed before an object is destroyed. To
handle such situations, java provides a mechanism called finalization. By using finalization, you
can define specific actions that will occur when an object is just about to be reclaimed by the
garbage collector.

To add a finalizer to a class, you simply define the finalize () method. The java run time
calls that method whenever it is about to recycle an object of that class. Inside the finalize ()
method you will specify those actions that must be performed before an object is destroyed. The
garbage collector runs periodically, checking for objects that are no longer referenced by any
running state or indirectly through other referenced objects. Right before an asset is freed, the
java run time calls the finalize () method on the object.

The finalize () method has this general form:


protected void finalize()

// finalization code here

Here, the keyword protected is a specifier that prevents access to finalize() by code
defined outside its class.

It is important to understand that finalize() is only called just prior to garbage collection.
It is not called when an object goes out-of-scope, for example. This means program should
provide other means of releasing system resources, etc., used by the object. It must not rely on
finalize() for normal program operation.

Sometimes an object will need to perform some action when it is destroyed. For example, if an
object is holding some non-Java resource such as a file handle or window character font, then
you might want to make sure these resources are freed before an object is destroyed.

By using finalization, you can define specific actions that will occur when an object is just about
to be reclaimed by the garbage collector.

class FinClass{

FinClass(){

System.out.println("This is a constructor");
}

public void finalize(){

System.out.println("finalize() method called");


}
}
class TestFinalize{

public static void main(String args[]){

FinClass fc = new FinClass();


System.out.println("System.gc() is called in the next statement");
fc = null;// Set fc to null to break all references to it so when you call the garbage collector it will
run the finalize method.
Runtime.getRuntime ().gc ();
}
}
Concept of Final(final keyword):-
Constants in java:-
Final :-
A variable level.
A method level.
A class level.

A construct is identified whose value is never be change during the vocation of program.
To declare a constant in java behave a result keyword known as final.
Final keyword plays an important role at the level of above.

Final variable declaration:-


Final float p;
In java final variable declaration is allow let her we can initialize value in to it only one time to
the modification will not be possible.

Final variable declaration /initialization:-


No any modification is possible.
final float pi=3.14t.
no together modification is allow.

Final at method level :-


class a class B extends A
{ {
Final void f1() void f1()
{ {
---------- ----------
---------- ----------
} }
} }

One a method is declare final if can be reused multiple time but can not be redefined or variable.
Final class A class B
{ {
Void f1() A 01=new A1();
{ {
--------- ---------
--------- ---------
} }
} }

Once a class is declare as final it can not be inherited directly.


Final variable value can not be changed.
Final method can not be redefined or overwrite.
Final class can not executed or inherited.

A java variable can be declared using the keyword final. Then the final variable can be
assigned only once.

 A variable that is declared as final and not initialized is called a blank final variable. A
blank final variable forces the constructors to initialise it.
 Java classes declared as final cannot be extended. Restricting inheritance!
 Methods declared as final cannot be overridden. In methods private is equal to final, but
in variables it is not.
 final parameters – values of the parameters cannot be changed after initialization. Do a
small java exercise to find out the implications of final parameters in method overriding.
 Java local classes can only reference local variables and parameters that are declared as
final.
 A visible advantage of declaring a java variable as static final is, the compiled java class
results in faster performance.

final keyword in Java to improve the garbage collection.

Static :

The static keyword can be used in 3 scenarios

1 ) static variables

2) static methods

3) static blocks of code.

Lets look at static variables and static methods first.

static variable
 It is a variable which belongs to the class and not to object(instance)
 Static variables are initialized only once , at the start of the execution . These variables
will be initialized first, before the initialization of any instance variables
 A single copy to be shared by all instances of the class
 A static variable can be accessed directly by the class name and doesn’t need any object
 Syntax : <class-name>.<variable-name>
static method
 It is a method which belongs to the class and not to the object(instance)
 A static method can access only static data. It can not access non-static data (instance
variables)
 A static method can call only other static methods and can not call a non-static method
from it.
 A static method can be accessed directly by the class name and doesn’t need any object
 Syntax : <class-name>.<method-name>
 A static method cannot refer to "this" or "super" keywords in anyway

Side Note:

main method is static , since it must be be accessible for an application to run , before any
instantiation takes place.

Lets learn the nuances of the static keywords by doing some excercises!

Assignment: To Learn working of static variables & methods

Step 1) Copy the following code into a editor

01.class Student {
02.int a; //initialized to zero
03.static int b; //initialized to zero only when class is loaded
not for each object created.
04.
05.Student(){
06.//Constructor incrementing static variable b
07.b++;
08.}
09.
10.
11.public void showData(){
12.System.out.println("Value of a = "+a);
13.System.out.println("Value of b = "+b);
14.}
15.//public static void increment(){
16.//a++;
17.//}
18.
19.}
20.
21.class Demo{
22.public static void main(String args[]){
23.Student s1 = new Student();
24.s1.showData();
25.Student s2 = new Student();
26.s2.showData();
27.//Student.b++;
28.//s1.showData();
29.}
30.}

Step 2) Save & Compile the code. Run the code as, java Demo.

Step 3) Expected output show below

Following diagram shows , how reference variables & objects are created and static variables are
accessed by the different instances.
Step 4) It is possible to access a static variable from outside the class using the syntax
ClassName.Variable_Name. Uncomment line # 27 & 28 . Save , Compile & Run . Observe
the output.

Step 5) Uncomment line 15,16 & 17 . Save , Compile & Run.

Step 5) Error = ? This is because it is not possible to access instance variable "a" from static
method "increment".

static block

The static block, is a block of statement inside a Java class that will be executed when a class is
first loaded in to the JVM
class Test{

static {

//Code goes here

A static block helps to initialize the static data members, just like constructors help to
initialize instance members

Static/Class methods
There are two types of methods.

 Instance methods are associated with an object and use the instance variables of that object.
This is the default.
 Static methods use no instance variables of any object of the class they are defined in. If you
define a method to be static, you will be given a rude message by the compiler if you try to
access any instance variables. You can access static variables, but except for constants, this is
unusual. Static methods typically take all they data from parameters and compute something
from those parameters, with no reference to variables. This is typical of methods which do some
kind of generic calculation. A good example of this are the many utility methods in the
predefined Math class. (See Math and java.util.Random).

Qualifying a static call

From outside the defining class, an instance method is called by prefixing it with an object,
which is then passed as an implicit parameter to the instance method, eg,
inputTF.setText("");

A static method is called by prefixing it with a class name, eg, Math.max(i,j);. Curiously, it
can also be qualified with an object, which will be ignored, but the class of the object will be
used.
Example

Here is a typical static method.

class MyUtils {
. . .
//================================================= mean
public static double mean(int[] p) {
int sum = 0; // sum of all the elements
for (int i=0; i<p.length; i++) {
sum += p[i];
}
return ((double)sum) / p.length;
}//endmethod mean
. . .
}

The only data this method uses or changes is from parameters (or local variables of course).

Why declare a method static

The above mean() method would work just as well if it wasn't declared static, as long as it was
called from within the same class. If called from outside the class and it wasn't declared static, it
would have to be qualified (uselessly) with an object. Even when used within the class, there are
good reasons to define a method as static when it could be.

 Documentation. Anyone seeing that a method is static will know how to call it (see below).
Similarly, any programmer looking at the code will know that a static method can't interact
with instance variables, which makes reading and debugging easier.
 Efficiency. A compiler will usually produce slightly more efficient code because no implicit object
parameter has to be passed to the method.

Calling static methods

There are two cases.

Called from within the same class

Just write the static method name. Eg,

// Called from inside the MyUtils class


double avgAtt = mean(attendance);
Called from outside the class

If a method (static or instance) is called from another class, something must be given before the
method name to specify the class where the method is defined. For instance methods, this is the
object that the method will access. For static methods, the class name should be specified. Eg,

// Called from outside the MyUtils class.


double avgAtt = MyUtils.mean(attendance);
If an object is specified before it, the object value will be ignored and the the class of the object
will be used.

. Inheritance
o know the concept of inheritance clearly you must have the idea of class and its features like
methods, data members, access controls, constructors, keywords this, super etc.

As the name suggests, inheritance means to take something that is already made. It is one of the
most important feature of Object Oriented Programming. It is the concept that is used for
reusability purpose. Inheritance is the mechanism through which we can derived classes from
other classes. The derived class is called as child class or the subclass or we can say the
extended class and the class from which we are deriving the subclass is called the base class or
the parent class. To derive a class in java the keyword extends is used. To clearly understand the
concept of inheritance you must go through the following example.

The concept of inheritance is used to make the things from general to more specific e.g. When
we hear the word vehicle then we got an image in our mind that it moves from one place to
another place it is used for traveling or carrying goods but the word vehicle does not specify
whether it is two or three or four wheeler because it is a general word. But the word car makes a
more specific image in mind than vehicle, that the car has four wheels . It concludes from the
example that car is a specific word and vehicle is the general word. If we think technically to
this example then vehicle is the super class (or base class or parent class) and car is the subclass
or child class because every car has the features of it's parent (in this case vehicle) class.

The following kinds of inheritance are there in java.

 Simple Inheritance
 Multilevel Inheritance

Pictorial Representation of Simple and Multilevel Inheritance

Simple Inheritance Multilevel Inheritance


Simple Inheritance

When a subclass is derived simply from it's parent class then this mechanism is known as simple
inheritance. In case of simple inheritance there is only a sub class and it's parent class. It is also
called single inheritance or one level inheritance.

eg.

class A {
int x;
int y;
int get(int p, int q){
x=p; y=q; return(0);
}
void Show(){
System.out.println(x);
}
}

class B extends A{
public static void main(String args[]){
A a = new A();
a.get(5,6);
a.Show();
}
void display(){
System.out.println("B");
}
}

Multilevel Inheritance

It is the enhancement of the concept of inheritance. When a subclass is derived from a derived
class then this mechanism is known as the multilevel inheritance. The derived class is called the
subclass or child class for it's parent class and this parent class works as the child class for it's
just above ( parent ) class. Multilevel inheritance can go up to any number of level.
e.g.

class A {
int x;
int y;
int get(int p, int q){
x=p; y=q; return(0);
}
void Show(){
System.out.println(x);
}
}
class B extends A{
void Showb(){
System.out.println("B");
}
}

class C extends B{
void display(){
System.out.println("C");
}
public static void main(String args[]){
A a = new A();
a.get(5,6);
a.Show();
}
}

Java does not support multiple Inheritance

Multiple Inheritance

The mechanism of inheriting the features of more than one base class into a single class is known
as multiple inheritance. Java does not support multiple inheritance but the multiple inheritance
can be achieved by using the interface.

In Java Multiple Inheritance can be achieved through use of Interfaces by implementing more
than one interfaces in a class.

super keyword

The super is java keyword. As the name suggest super is used to access the members of the super
class.It is used for two purposes in java.

The first use of keyword super is to access the hidden data variables of the super class hidden by
the sub class.

e.g. Suppose class A is the super class that has two instance variables as int a and float b. class B
is the subclass that also contains its own data members named a and b. then we can access the
super class (class A) variables a and b inside the subclass class B just by calling the following
command.

super.member;

Here member can either be an instance variable or a method. This form of super most useful to
handle situations where the local members of a subclass hides the members of a super class
having the same name. The following example clarify all the confusions.

class A{
int a;
float b;
void Show(){
System.out.println("b in super class: " + b);
}
}

class B extends A{
int a;
float b;
B( int p, float q){
a = p;
super.b = q;
}
void Show(){
super.Show();
System.out.println("b in super class: " + super.b);
System.out.println("a in sub class: " + a);
}

public static void main(String[] args){


B subobj = new B(1, 5);
subobj.Show();
}
}

Output:

C:\>java B
b in super class: 5.0
b in super class: 5.0
a in sub class: 1

Use of super to call super class constructor: The second use of the keyword super in java is to
call super class constructor in the subclass. This functionality can be achieved just by using the
following command.

super(param-list);

Here parameter list is the list of the parameter requires by the constructor in the super class.
super must be the first statement executed inside a super class constructor. If we want to call the
default constructor then we pass the empty parameter list. The following program illustrates the
use of the super keyword to call a super class constructor.

class A{
int a;
int b;
int c;
A(int p, int q, int r){
a=p;
b=q;
c=r;
}
}

class B extends A{
int d;
B(int l, int m, int n, int o){
super(l,m,n);
d=o;
}
void Show(){
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}

public static void main(String args[]){


B b = new B(4,3,8,7);
b.Show();
}
}

Output:

C:\>java B
a=4
b=3
c=8
d=7

Inheritance can be defined as the process where one object acquires the properties of another.
With the use of inheritance the information is made manageable in a hierarchical order.

When we talk about inheritance the most commonly used keyword would be extends and
implements. These words would determine whether one object IS-A type of another. By using
tInheritance can be defined as the process where one object acquires the properties of another.
With the use of inheritance the information is made manageable in a hierarchical order.

When we talk about inheritance the most commonly used keyword would be extends and
implements. These words would determine whether one object IS-A type of another. By using
these keywords we can make one object acquire the properties of another object.

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{


}

public class Dog extends Mammal{


}

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

 Animal is the superclass of Mammal class.


 Animal is the superclass of Reptile class.
 Mammal and Reptile are sub classes 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:
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);
}
}

This would produce 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.

The implements keyword is used by classes by inherit from interfaces. Interfaces can never be
extended by the classes.

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

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

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 Vann class will either do the work by itself or ask another class to perform the action.

A very important fact to remember is that Java only supports only single inheritance. This means
that a class cannot extend more than one class. Therefore following is illegal:

public class extends Animal, Mammal{}

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

hese keywords we can make one object acquire the properties of another object.

For example a car class can inherit some properties from a General vehicle class. Here we find
that the base class is the vehicle class and the subclass is the more specific car class. A subclass
must use the extends clause to derive from a super class which must be written in the header of
the subclass definition. The subclass inherits members of the superclass and hence promotes
code reuse. The subclass itself can add its own new behavior and properties. The
java.lang.Object class is always at the top of any Class inheritance hierarchy.

class Box {

double width;
double height;
double depth;
Box() {
}
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
void getVolume() {
System.out.println("Volume is : " + width * height * depth);
}
}

public class MatchBox extends Box {

double weight;
MatchBox() {
}
MatchBox(double w, double h, double d, double m) {
super(w, h, d);
weight = m;
}
public static void main(String args[]) {
MatchBox mb1 = new MatchBox(10, 10, 10, 10);
mb1.getVolume();
System.out.println("width of MatchBox 1 is " + mb1.width);
System.out.println("height of MatchBox 1 is " + mb1.height);
System.out.println("depth of MatchBox 1 is " + mb1.depth);
System.out.println("weight of MatchBox 1 is " + mb1.weight);
}
}

Output

Volume is : 1000.0
width of MatchBox 1 is 10.0
height of MatchBox 1 is 10.0
depth of MatchBox 1 is 10.0
weight of MatchBox 1 is 10.0

What is not possible using java class Inheritance?

1. Private members of the superclass are not inherited by the subclass and can only be indirectly
accessed.
2. Members that have default accessibility in the superclass are also not inherited by subclasses
in other packages, as these members are only accessible by their simple names in subclasses
within the same package as the superclass.
3. Since constructors and initializer blocks are not members of a class, they are not inherited by a
subclass.
4. A subclass can extend only one superclass

class Vehicle {

// Instance fields
int noOfTyres; // no of tyres
private boolean accessories; // check if accessorees present or not
protected String brand; // Brand of the car
// Static fields
private static int counter; // No of Vehicle objects created
// Constructor
Vehicle() {
System.out.println("Constructor of the Super class called");
noOfTyres = 5;
accessories = true;
brand = "X";
counter++;
}
// Instance methods
public void switchOn() {
accessories = true;
}
public void switchOff() {
accessories = false;
}
public boolean isPresent() {
return accessories;
}
private void getBrand() {
System.out.println("Vehicle Brand: " + brand);
}
// Static methods
public static void getNoOfVehicles() {
System.out.println("Number of Vehicles: " + counter);
}
}

class Car extends Vehicle {

private int carNo = 10;


public void printCarInfo() {
System.out.println("Car number: " + carNo);
System.out.println("No of Tyres: " + noOfTyres); // Inherited.
// System.out.println("accessories: " + accessories); // Not
Inherited.
System.out.println("accessories: " + isPresent()); // Inherited.
// System.out.println("Brand: " + getBrand()); // Not
Inherited.
System.out.println("Brand: " + brand); // Inherited.
// System.out.println("Counter: " + counter); // Not Inherited.
getNoOfVehicles(); // Inherited.
}
}

public class VehicleDetails { // (3)

public static void main(String[] args) {


new Car().printCarInfo();
}
}

Output

Constructor of the Super class called


Car number: 10
No of Tyres: 5
accessories: true
Brand: X
Number of Vehicles: 1

Single Inheritance Example In Java :


import java.io.*;

class employee
{
int empcode;
String empname,empadd;
int phno;
final static int da=10;
final static int hra=20;
int salary;
int basic;
employee()
{
empcode=phno=0;
empname=empadd="null";
}
employee(int c,int p,String n,String a)
{
empcode=c;
empname=n;
phno=p;
empadd=a;

void salary_comp()
{
salary=basic+(basic*da/100)+(basic*hra/100);
System.out.println("NET SALARY"+salary);
}
}

class manager extends employee


{

manager(int c,int p,String n,String a,int b)


{
super(c,p,n,a);
basic=b;
}
manager()
{
super();
basic=0;
}
}

class typist extends employee


{

typist(int c,int p,String n,String a,int b)


{
super(c,p,n,a);
basic=b;
}
typist()
{
super();
basic=0;
}
}

class emp
{
public static void main(String args[])
{
manager m=new manager(1,9904567,"keshav","kol",15000);
typist t=new typist(30,687900,"ram","mum",20000);
System.out.println("MANAGER:");
m.salary_comp();
System.out.println("TYPER:");
t.salary_comp();
}
}
Excepting Object, which has no super class, every class has one and only one direct superclass (single
inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of
Object.

Classes can be derived from classes that are derived from classes that are derived from classes, and so
on, and ultimately derived from the topmost class, Object. Such a class is said to be descended from all
the classes in the inheritance chain stretching back to Object.

The Java Platform Class Hierarchy

The Object class, defined in the java.lang package, defines and implements behavior common
to all classes—including the ones that you write. In the Java platform, many classes derive
directly from Object, other classes derive from some of those classes, and so on, forming a
hierarchy of classes.
All Classes in the Java Platform are Descendants of Object

At the top of the hierarchy, Object is the most general of all classes. Classes near the bottom of
the hierarchy provide more specialized behavior.

what You Can Do in a Subclass

A subclass inherits all of the public and protected members of its parent, no matter what package
the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-
private members of the parent. You can use the inherited members as is, replace them, hide
them, or supplement them with new members:

 The inherited fields can be used directly, just like any other fields.
 You can declare a field in the subclass with the same name as the one in the superclass, thus
hiding it (not recommended).
 You can declare new fields in the subclass that are not in the superclass.
 The inherited methods can be used directly as they are.
 You can write a new instance method in the subclass that has the same signature as the one in
the superclass, thus overriding it.
 You can write a new static method in the subclass that has the same signature as the one in the
superclass, thus hiding it.
 You can declare new methods in the subclass that are not in the superclass.
 You can write a subclass constructor that invokes the constructor of the superclass, either
implicitly or by using the keyword super.

The following sections in this lesson will expand on these topics.

Private Members in a Superclass

A subclass does not inherit the private members of its parent class. However, if the superclass
has public or protected methods for accessing its private fields, these can also be used by the
subclass.
A nested class has access to all the private members of its enclosing class—both fields and
methods. Therefore, a public or protected nested class inherited by a subclass has indirect access
to all of the private members of the superclass.

Casting Objects

We have seen that an object is of the data type of the class from which it was instantiated. For
example, if we write

public MountainBike myBike = new MountainBike();

then myBike is of type MountainBike.

MountainBike is descended from Bicycle and Object. Therefore, a MountainBike is a


Bicycle and is also an Object, and it can be used wherever Bicycle or Object objects are
called for.

The reverse is not necessarily true: a Bicycle may be a MountainBike, but it isn't necessarily.
Similarly, an Object may be a Bicycle or a MountainBike, but it isn't necessarily.

Casting shows the use of an object of one type in place of another type, among the objects
permitted by inheritance and implementations. For example, if we write

Object obj = new MountainBike();

then obj is both an Object and a Mountainbike (until such time as obj is assigned another
object that is not a Mountainbike). This is called implicit casting.

If, on the other hand, we write

MountainBike myBike = obj;

we would get a compile-time error because obj is not known to the compiler to be a
MountainBike. However, we can tell the compiler that we promise to assign a MountainBike to
obj by explicit casting:

MountainBike myBike = (MountainBike)obj;

This cast inserts a runtime check that obj is assigned a MountainBike so that the compiler can
safely assume that obj is a MountainBike. If obj is not a Mountainbike at runtime, an
exception will be thrown.

Note: You can make a logical test as to the type of a particular object using the instanceof operator.
This can save you from a runtime error owing to an improper cast. For example:
if (obj instanceof MountainBike) {
MountainBike myBike = (MountainBike)obj;
}

Inheritance is the capability of a class to use the properties and methods of another class while
adding its own functionality. An example of where this could be useful is with an employee
records system. You could create a generic employee class with states and actions that are
common to all employees. Then more specific classes could be defined for salaried,
commissioned and hourly employees. The generic class is known as the parent (or superclass or
base class) and the specific classes as children (or subclasses or derived classes). The concept of
inheritance greatly enhances the ability to reuse code as well as making design a much simpler
and cleaner process.

The Object class is the highest superclass (ie. root class) of Java. All other classes are subclasses
(children or descendants) inherited from the Object class. The Object class includes methods
such as:

clone() equals() copy(Object src) finalize() getClass()

hashCode() notify() notifyAll() toString() wait()

Composition vs. Inheritance

There are two ways to reuse the existing classes, namely, composition and inheritance. With
composition, you create a new class, which is composed of existing classes. With inheritance,
you create a new class, which is based on an existing class, with some modifications or
extensions.

Composition

As an example of reusing a class via composition, suppose that we have an existing class called
Point, defined as below:
The source code for Point.java is as follows:

1 public class Point {


2 private int x, y; // (x, y) co-ordinates
3 public Point(int x, int y) { // constructor
4 this.x = x;
5 this.y = y;
6 }
7 public Point() { // no-arg constructor
8 x = 0;
9 y = 0;
10 }
11 public int getX() {
12 return x;
13 }
14 public void setX(int x) {
15 this.x = x;
16 }
17 public int getY() {
18 return y;
19 }
20 public void setY(int y) {
21 this.y = y;
22 }
23 public String toString() {
24 return "(" + x + "," + y + ")";
25 }
26 }

Suppose that we need a new class called Line, we can re-use the Point class via composition.
We say that "a line is composed of two points", or "a line has two points". Composition exhibits
a "has-a" relationship. In UML notations, composition is represented as a diamond-head line
pointing to its constituents.
The source code for Line.java is as follows:

1 public class Line {


2 Point begin, end; // begin and end Points
3 public Line(int x1, int y1, int x2, int y2) { // constructor 1
4 begin = new Point(x1, y1);
5 end = new Point(x2, y2);
6 }
7 public Line(Point begin, Point end) { // constructor 2
8 this.begin = begin;
9 this.end = end;
10 }
11 public String toString() {
12 return "Line from " + begin + " to " + end;
13 }
14 }

Inheritance

In OOP, we often organize classes in hierarchy to avoid duplication and reduce redundancy. The
classes in the lower hierarchy inherit all the variables (static attributes) and methods (dynamic
behaviors) from the higher hierarchies. A class in the lower hierarchy is called a subclass (or
derived, child, extended class). A class in the upper hierarchy is called a superclass (or base,
parent class). By pulling out all the common variables and methods into the superclasses, and
leave the specialized variables and methods in the subclasses, redundancy can be greatly reduced
or eliminated as these common variables and methods do not need to be repeated in all the
subclasses. For example,

A subclass inherits all the variables and methods from its superclasses, including its immediate
parent as well as all the ancestors. It is important to note that a subclass is not a "subset" of a
superclass. In contrast, subclass is a "superset" of a superclass. It is because a subclass inherits
all the variables and methods of the superclass; in addition, it extends the superclass by providing
more variables and methods.

In Java, you define a subclass using the keyword "extends", e.g.,

class Goalkeeper extends SoccerPlayer {...}


class MyApplet extends java.applet.Applet {...}
class Cylinder extends Circle {...}

The UML notation for inheritance is a solid line with a hollow arrowhead leading from the
subclass to its superclass as shown:

An Example on Inheritance

In this example, we derive a subclass called Cylinder from the superclass Circle, which we
have created in the previous chapter. It is important to note that we reuse the class Circle.
Reusability is one of the most important properties of OOP. (Why reinvent the wheels?) The
class Cylinder inherits all the member variables (radius and color) and methods
(getRadius(), getArea(), among others) from its superclass Circle. It further defines a
variable called height, two public methods – getHeight() and getVolume() and its own
constructors, as shown:
public class Cylinder extends Circle {
1
private double height; // member variable
2
3
public Cylinder() { // constructor 1
4
super(); // invoke superclass' constructor Circle()
5
height = 1.0;
6
}
7
public Cylinder(double radius, double height) { // Constructor 2
8
super(radius); // invoke superclass' constructor
9
Circle(radius)
10
this.height = height;
11
}
12
13
public double getHeight() {
14
return height;
15
}
16
public void setHeight(double height) {
17
this.height = height;
18
}
19
public double getVolume() {
20
return getArea()*height; // Use Circle's getArea()
21
}
22
}

You cannot execute the Cylinder class, as it is not a standalone program (there is no main()
method). The class Cylinder is meant to be used in other programs. We have to write another
class called "TestCylinder" for testing the Cylinder class as follows:
1 public class TestCylinder {
2 public static void main(String[] args) {
3 Cylinder cy1 = new Cylinder(); // use constructor 1
4 System.out.println("Radius is " + cy1.getRadius()
5 + " Height is " + cy1.getHeight()
6 + " Color is " + cy1.getColor()
7 + " Base area is " + cy1.getArea()
8 + " Volume is " + cy1.getVolume());
9
10 Cylinder cy2 = new Cylinder(5.0, 2.0); // use constructor 2
11 System.out.println("Radius is " + cy2.getRadius()
12 + " Height is " + cy2.getHeight()
13 + " Color is " + cy2.getColor()
14 + " Base area is " + cy2.getArea()
15 + " Volume is " + cy2.getVolume());
16 }
17 }

Keep the "Cylinder.java" and "TestCylinder.java" in the same directory as


"Circle.class" (because we are reusing the class Circle). Compile and run the program. The
expected output is as follows:

Radius is 1.0 Height is 1.0 Color is red Base area is 3.141592653589793


Volume is 3.141592653589793
Radius is 5.0 Height is 2.0 Color is red Base area is 78.53981633974483
Volume is 157.07963267948966

Method Overriding & Variable Hiding

A subclass inherits all the member variables and methods from its superclasses (the immediate
parent and all its ancestors). It can use the inherited methods and variables as they are. It may
also override an inherited method by providing its own version, or hide an inherited variable by
defining a variable of the same name.

For example, the inherited method getArea() in a Cylinder object computes the base area of
the cylinder. Suppose that you decide to override the getArea() to compute the surface area of
the cylinder in the class Cylinder. Below are the changes:

1 public class Cylinder extends Circle {


2 ......
3 // override the getArea() method inherited from superclass Circle
4 public double getArea() {
5 return 2*Math.PI*getRadius()*height + 2*super.getArea();
6 }
7 // need to change the getVolume() as well
8 public double getVolume() {
9 return super.getArea()*height; // use superclass' getArea()
10 }
11 // override the inherited toString()
12 public String toString() {
13 return "Cylinder: radius = " + getRadius() + " height = " + height;
14 }
15 }

If getArea() is called from a Circle object, it computes the area of the circle. If getArea() is
called from a Cylinder object, it computes the surface area of the cylinder using the overridden
implementation. Note that you have to use public accessor method getRadius() to retrieve the
radius of the Circle, because radius is declared private and therefore not accessible to other
classes, including the subclass Cylinder.

But if you override the getArea() in the Cylinder, the getVolume() (=getArea()*height) no
longer works. It is because the overridden getArea() will be used in Cylinder, which does not
compute the base area. You can fix this problem by using super.getArea(), to use the
superclass' version of getArea(). Note that super.getArea() can only be issued from the
subclass definition, but no from an instance created, e.g. c1.super.getArea(), as it break the
information hiding and encapsulation principle.

Default no-arg Constructor:

If no constructor is defined in a class, Java compiler automatically create a no-argument (no-arg)


constructor, that simply issues a super() call, as follows:

// If no constructor is defined in a class, compiler inserts this no-arg


constructor
public ClassName () {
super(); // call the superclass' no-arg constructor
}

Take note that:

 The default no-arg constructor will not be automatically generated, if one (or more) constructor
was defined. In other words, you need to define no-arg constructor explicitly if other
constructors were defined.
 If the immediate superclass does not have the default constructor (it defines some constructors
but does not define a no-arg constructor), you will get a compilation error in doing a super()
call. Note that Java compiler inserts a super() as the first statement in a constructor if there is
no super(args).

Common Root Class - java.lang.Object

Java adopts a so-called common-root approach. All Java classes are derived from a common root
class called java.lang.Object. This Object class defines and implements the common
behaviors that are required of all the Java objects running under the JRE. These common
behaviors enable the implementation of features such as multithreading and garbage collector.
Annotation @Override (JDK 1.5)

The "@Override" is known as annotation (introduced in JDK 1.5), which asks compiler to check
whether there is such a method in the superclass to be overridden. This helps greatly if you
misspell the name of the method to be overridden. For example, suppose that you wish to
override method toString() in a subclass. If @Override is not used and toString() is
misspelled as TOString(), it will be treated as a new method in the subclass, instead of
overriding the superclass. If @Override is used, the compiler will signal an error. @Override
annotation is optional, but certainly nice to have.

Composition vs. Inheritance

Recall that there are two ways of reusing existing classes: composition and inheritance. We have
seen that a Line class can be implemented using composition of Point class - "a line is
composed of two points".

A Line can also be implemented, using inheritance, from the Point class - "a line is a point
extended by another point" - as follows:

public class Line extends Point {


1 // Inherit the begin Point from the superclass
2 Point end; // end Point
3 public Line(int x1, int y1, int x2, int y2) { // constructor 1
4 super(x1, y1); // call the superclass constructor to construct the
5 begin Point
6 end = new Point(x2, y2);
7 }
8 public Line(Point begin, Point end) { // constructor 2
9 super(begin.getX(), begin.getY()); // call the superclass
10 constructor to construct the begin Point
11 this.end = end;
12 }
13 public String toString() {
14 return "Line from " + super.toString() + " to " + end;
15 }
}

Study both versions of the Line class. I suppose that it is easier to say that "a line is composed of
two points" than that "a line is a point extended by another point".

Rule of Thumb: Use composition if possible, before considering inheritance.

Exercises

LINK TO EXERCISES ON COMPOSITION VS INHERITANCE


Polymorphism in Inheritance:

The word "polymorphism" means "many forms". It comes from Greek word "poly" (means many)
and "morphos" (means form). For examples, in chemistry, carbon exhibits polymorphism
because it can be found in more than one form: graphite and diamond. Each of the form has it
own distinct properties.

Substitutability:

A subclass possesses all the attributes and operations of its superclass (because a subclass
inherited all attributes and operations from its superclass). This means that a subclass object can
do whatever its superclass can do. As a result, we can substitute a subclass instance when a
superclass instance is expected, and everything shall work fine. This is called substitutability.

In our earlier example of Circle and Cylinder: Cylinder is a subclass of Circle. We can say
that Cylinder "is-a" Circle (actually, it "is-more-than-a" Circle). Subclass-superclass exhibits
a so called "is-a" relationship.

Via substitutability, we can create an instance of Cylinder, and assign it to a Circle (its
superclass) reference, as follows:

// Substitute a subclass instance to its superclass reference


Circle aCircle = new Cylinder(5.0);
You can invoke all the methods defined in the Circle class for the reference aCircle, (which is
actually holding a Cylinder object), e.g. aCircle.getRadius() and aCircle.getColor().
This is because a subclass instance possesses all the properties of its superclass.

However, you cannot invoke methods defined in the Cylinder class for the reference aCircle,
e.g. aCircle.getHeight() and aCircle.getVolume(). This is because aCircle is a reference
to the Circle class, which does not know about methods defined in the subclass Cylinder.

aCircle is a reference to the Circle class, but holds an object of its subclass Cylinder. The
reference aCircle, however, retains its internal identity. In our example, the subclass Cylinder
overrides methods getArea() and toString(). aCircle.getArea() or aCircle.toString()
invokes the overridden version defined in the subclass Cylinder, instead of the version defined
in Circle. This is because aCircle is in fact holding a Cylinder object internally.

Upcasting & Downcasting

Substituting a subclass instance for its superclass is called "upcasting". Upcasting is always safe
because a subclass instance possesses all the properties of its superclass and can do whatever its
superclass can do.

You can revert a substituted reference back to the original subclass. This is called "downcasting".
For example,

Cycle aCircle = new Cylinder(5.0); // upcast is safe


Cylinder aCylinder = (Cylinder) aCircle; // downcast needs the casting
operator

Downcasting requires explicit type casting operator in the form of prefix operator (new-type).
Downcasting is not always safe, and throws a runtime ClassCastException if the instance to be
downcasted does not belong to the correct subclass. A subclass object can be substituted for its
superclass, but the reverse is not always true.

Summary of Polymorphism

1. A subclass instance processes all the attributes operations of its superclass. When a superclass
instance is expected, it can be substituted by a subclass instance. In other words, a reference to
a class may hold an instance of that class or an instance of one of its subclasses - it is called
substitutability.
2. If a subclass instance is assign to a superclass reference, you can invoke the methods defined in
the superclass only. You cannot invoke methods defined in the subclass.
3. However, the substituted instance retains its own identity in terms of overridden methods and
hiding variables. If the subclass overrides methods in the superclass, the subclass's version will
be executed, instead of the superclass's version.
Polymorphism Example

Polymorphism is very powerful in OOP to separate the interface and implementation so as to


allow the programmer to program at the interface in the design of a complex system.

Consider the following example,

Suppose that our program uses many kinds of shapes, such as triangle, rectangle and so on. We
should design a superclass called Shape, which defines the public interface (or behaviours) of all
the shapes. For example, we would like all the shapes to have a method called getArea(), which
returns the area of that particular shape. The Shape class can be written as follow.

public class Shape {


// Instance variable
private String color;

// Constructor
public Shape (String color) {
this.color = color;
}

public String toString() {


return "Shape of color=\"" + color + "\"";
}

// All shapes must has a method called getArea()


public double getArea() {
System.err.println("Shape unknown! Cannot compute area!");
return 0; // Need a return to compile the program
}
}
Take note that we have a problem on writing the getArea() method in the Shape class, because
the area cannot be computed unless the actual shape is known. We shall print an error message
for the time being. In the later section, I shall show you how to resolve this problem.

We can then derive subclasses, such as Triangle and Rectangle, from the superclass Shape.

public class Rectangle extends Shape {


// Instance variables
private int length;
private int width;

// Constructor
public Rectangle(String color, int length, int width) {
super(color);
this.length = length;
this.width = width;
}

@Override
public String toString() {
return "Rectangle of length=" + length + " and width=" + width + ",
subclass of " + super.toString();
}

@Override
public double getArea() {
return length*width;
}
}
public class Triangle extends Shape {
// Instance variables
private int base;
private int height;

// Constructor
public Triangle(String color, int base, int height) {
super(color);
this.base = base;
this.height = height;
}

@Override
public String toString() {
return "Triangle of base=" + base + " and height=" + height + ",
subclass of " + super.toString();
}

@Override
public double getArea() {
return 0.5*base*height;
}
}

The subclasses override the getArea() method inherited from the superclass, and provide the
proper implementations for getArea().
In our application, we could create references of Shape, and assign them instances of subclasses,
as follows:

public class TestShape {


public static void main(String[] args) {
Shape s1 = new Rectangle("red", 4, 5);
System.out.println(s1);
System.out.println("Area is " + s1.getArea());

Shape s2 = new Triangle("blue", 4, 5);


System.out.println(s2);
System.out.println("Area is " + s2.getArea());
}
}

The beauty of this code is that all the references are from the superclass (i.e., programming at
the interface level). You could instantiate different subclass instance, and the code still works.
You could extend your program easily by adding in more subclasses, such as Circle, Square,
etc, with ease.

Nonetheless, the above definition of Shape class poses a problem, if someone instantiate a Shape
object and invoke the getArea() from the Shape object, the program breaks.

public class TestShape {


public static void main(String[] args) {
// Constructing a Shape instance poses problem!
Shape s3 = new Shape("green");
System.out.println(s3);
System.out.println("Area is " + s3.getArea());
}
}

This is because the Shape class is meant to provide a common interface to all its subclasses,
which are supposed to provide the actual implementation. We do not want anyone to instantiate a
Shape instance. This problem can be resolved by using the so-called abstract class.

Abstract Classes & Interfaces

Abstract methods

An abstract method is a method with only signature (i.e., the method name, the list of
arguments and the return type) without implementation (i.e., the method’s body). You use the
keyword abstract to declare an abstract method.

For example, in the Shape class, we can declare three abstract methods getArea(), draw(), as
follows:

public abstract double getArea();


public abstract void draw();
Implementation of these methods is not possible in the Shape class, as the actual shape is not yet
known. (How to compute the area if the shape is not known?) Implementation of these abstract
methods will be provided later once the actual shape is known. These abstract methods cannot
be invoked because they have no implementation.

Abstract class

java provides a special type of class called an abstract class. Which helps us to organize our
classes based on common methods? An abstract class lets you put the common method names in
one abstract class without having to write the actual implementation code.

An abstract class can be extended into sub-classes; these sub-classes usually provide
implementations for all of the abstract methods.

The key idea with an abstract class is useful when there is common functionality that's like to
implement in a superclass and some behavior is unique to specific classes. So you implement the
superclass as an abstract class and define methods that have common subclasses. Then you
implement each subclass by extending the abstract class and add the methods unique to the class.

Points of abstract class :

1. Abstract class contains abstract methods.


2. Program can't instantiate an abstract class.
3. Abstract classes contain mixture of non-abstract and abstract methods.
4. If any class contains abstract methods then it must implements all the abstract methods of
the abstract class

An abstract class is a class that is declared abstract—it may or may not include abstract
methods. Abstract classes cannot be instantiated, but they can be subclassed.

An abstract method is a method that is declared without an implementation (without braces, and
followed by a semicolon), like this:

abstract void moveTo(double deltaX, double deltaY);

If a class includes abstract methods, the class itself must be declared abstract, as in:

public abstract class GraphicObject {


// declare fields
// declare non-abstract methods
abstract void draw();
}
When an abstract class is subclassed, the subclass usually provides implementations for all of the
abstract methods in its parent class. However, if it does not, the subclass must also be declared
abs declared our Circle class to be part of a package named shapes. Suppose we plan to
implement a number of shape classes: Rectangle, Square, Ellipse, Triangle, and so on. We
can give these shape classes our two basic area() and circumference() methods. Now, to
make it easy to work with an array of shapes, it would be helpful if all our shape classes had a
common superclass, Shape. If we structure our class hierarchy this way, every shape object,
regardless of the actual type of shape it represents, can be assigned to variables, fields, or array
elements of type Shape. We want the Shape class to encapsulate whatever features all our shapes
have in common (e.g., the area() and circumference() methods). But our generic Shape class
doesn't represent any real kind of shape, so it cannot define useful implementations of the
methods. Java handles this situation with abstract methods.

Java lets us define a method without implementing it by declaring the method with the abstract
modifier. An abstract method has no body; it simply has a signature definition followed by a
semicolon.[7] Here are the rules about abstract methods and the abstract classes that contain
them:

[7] An abstract method in Java is something like a pure virtual function in C++ (i.e., a virtual
function that is declared = 0). In C++, a class that contains a pure virtual function is called an
abstract class and cannot be instantiated. The same is true of Java classes that contain abstract
methods.

 Any class with an abstract method is automatically abstract itself and must be
declared as such.
 An abstract class cannot be instantiated.
 A subclass of an abstract class can be instantiated only if it overrides each of the
abstract methods of its superclass and provides an implementation (i.e., a method body)
for all of them. Such a class is often called a concrete subclass, to emphasize the fact that
it is not abstract.
 If a subclass of an abstract class does not implement all the abstract methods it
inherits, that subclass is itself abstract.
 static, private, and final methods cannot be abstract, since these types of methods
cannot be overridden by a subclass. Similarly, a final class cannot contain any
abstract methods.
 A class can be declared abstract even if it does not actually have any abstract
methods. Declaring such a class abstract indicates that the implementation is somehow
incomplete and is meant to serve as a superclass for one or more subclasses that will
complete the implementation. Such a class cannot be instantiated.

There is an important feature of the rules of abstract methods. If we define the Shape class to
have abstractarea() and circumference() methods, any subclass of Shape is required to
provide implementations of these methods so it can be instantiated. In other words, every Shape
object is guaranteed to have implementations of these methods defined. Example 3-5 shows how
this might work. It defines an abstractShape class and two concrete subclasses of it.
Example 3-5. An Abstract Class and Concrete Subclasses
public abstract class Shape {
public abstract double area(); // Abstract methods: note
public abstract double circumference(); // semicolon instead of body.
}

class Circle extends Shape {


public static final double PI = 3.14159265358979323846;
protected double r; // Instance data
public Circle(double r) { this.r = r; } // Constructor
public double getRadius() { return r; } // Accessor
public double area() { return PI*r*r; } // Implementations of
public double circumference() { return 2*PI*r; } // abstract methods.
}

class Rectangle extends Shape {


protected double w, h; // Instance data
public Rectangle(double w, double h) { // Constructor
this.w = w; this.h = h;
}
public double getWidth() { return w; } // Accessor method
public double getHeight() { return h; } // Another accessor
public double area() { return w*h; } // Implementations of
public double circumference() { return 2*(w + h); } // abstract methods.
}

Each abstract method in Shape has a semicolon right after its parentheses. There are no curly
braces, and no method body is defined. Using the classes defined in Example 3-5, we can now
write code like this:

Shape[] shapes = new Shape[3]; // Create an array to hold shapes


shapes[0] = new Circle(2.0); // Fill in the array
shapes[1] = new Rectangle(1.0, 3.0);
shapes[2] = new Rectangle(4.0, 2.0);

double total_area = 0;
for(int i = 0; i < shapes.length; i++)
total_area += shapes[i].area(); // Compute the area of the shapes

There are two important points to notice here:

 Subclasses of Shape can be assigned to elements of an array of Shape. No cast is


necessary. This is another example of a widening reference type conversion (discussed in
Chapter 2, "Java Syntax from the Ground Up").
 You can invoke the area() and circumference() methods for any Shape object, even
though the Shape class does not define a body for these methods. When you do this, the
method to be invoked is found using dynamic method lookup, so the area of a circle is
computed using the method defined by Circle, and the area of a rectangle is computed
using the method defined by Rectangle.

tract.
Abstract Classes versus Interfaces

Unlike interfaces, abstract classes can contain fields that are not static and final, and they can
contain implemented methods. Such abstract classes are similar to interfaces, except that they
provide a partial implementation, leaving it to subclasses to complete the implementation. If an
abstract class contains only abstract method declarations, it should be declared as an interface
instead.

Multiple interfaces can be implemented by classes anywhere in the class hierarchy, whether or
not they are related to one another in any way. Think of Comparable or Cloneable, for example.

By comparison, abstract classes are most commonly subclassed to share pieces of


implementation. A single abstract class is subclassed by similar classes that have a lot in
common (the implemented parts of the abstract class), but also have some differences (the
abstract methods).

An Abstract Class Example

In an object-oriented drawing application, you can draw circles, rectangles, lines, Bezier curves,
and many other graphic objects. These objects all have certain states (for example: position,
orientation, line color, fill color) and behaviors (for example: moveTo, rotate, resize, draw) in
common. Some of these states and behaviors are the same for all graphic objects—for example:
position, fill color, and moveTo. Others require different implementations—for example, resize
or draw. All GraphicObjects must know how to draw or resize themselves; they just differ in
how they do it. This is a perfect situation for an abstract superclass. You can take advantage of
the similarities and declare all the graphic objects to inherit from the same abstract parent
object—for example, GraphicObject, as shown in the following figure.

Classes Rectangle, Line, Bezier, and Circle inherit from GraphicObject

First, you declare an abstract class, GraphicObject, to provide member variables and methods
that are wholly shared by all subclasses, such as the current position and the moveTo method.
GraphicObject also declares abstract methods for methods, such as draw or resize, that need
to be implemented by all subclasses but must be implemented in different ways. The
GraphicObject class can look something like this:

abstract class GraphicObject {


int x, y;
...
void moveTo(int newX, int newY) {
...
}
abstract void draw();
abstract void resize();
}

Each non-abstract subclass of GraphicObject, such as Circle and Rectangle, must provide
implementations for the draw and resize methods:

class Circle extends GraphicObject {


void draw() {
...
}
void resize() {
...
}
}
class Rectangle extends GraphicObject {
void draw() {
...
}
void resize() {
...
}
}

 An abstract class may also have concrete (complete) methods.


 For design purpose, a class can be declared abstract even if it does not contain any
abstract methods
 Reference of an abstract class can point to objects of its sub-classes thereby achieving
run-time polymorphism Ex: Shape obj = new Rectangle();
 A class must be compulsorily labeled abstract , if it has one or more abstract methods.

When an Abstract Class Implements an Interface

In the section on Interfaces, it was noted that a class that implements an interface must
implement all of the interface's methods. It is possible, however, to define a class that does not
implement all of the interface methods, provided that the class is declared to be abstract. For
example,

abstract class X implements Y {


// implements all but one method of Y
}

class XX extends X {
// implements the remaining method in Y
}
In this case, class X must be abstract because it does not fully implement Y, but class XX does,
in fact, implement Y.

Class Members

An abstract class may have static fields and static methods. You can use these static
members with a class reference—for example, AbstractClass.staticMethod()—as you
would with any other class.

A class containing one or more abstract methods is called an abstract class. An abstract
class must be declared with a class-modifier abstract. Let rewrite our Shape class as an
abstract class, containing an abstract method getArea() as follows:

public abstract class Shape {


// Instance variable
private String color;

// Constructor
public Shape (String color) {
this.color = color;
}

public String toString() {


return "Shape of color=\"" + color + "\"";
}

// All Shape subclasses must implement a method called getArea()


abstract public double getArea();
}

An abstract class is incomplete in its definition, since the implementation of its abstract
methods is missing. Therefore, an abstract class cannot be instantiated. In other words, you
cannot create instances from an abstract class (otherwise, you will have an incomplete instance
with missing method's body).

To use an abstract class, you have to derive a subclass from the abstract class. In the derived
subclass, you have to override the abstract methods and provide implementation to all the
abstract methods. The subclass derived is now complete, and can be instantiated. (If a subclass
does not provide implementation to all the abstract methods of the superclass, the subclass
remains abstract.)

This property of the abstract class solves our earlier problem. In other words, you can create
instances of the subclasses such as Triangle and Rectangle, and upcast them to Shape (so as to
program and operate at the interface level), but you cannot create instance of Shape, which avoid
the pitfall that we have faced. For example,

public class TestShape {


public static void main(String[] args) {
Shape s1 = new Rectangle("red", 4, 5);
System.out.println(s1);
System.out.println("Area is " + s1.getArea());

Shape s2 = new Triangle("blue", 4, 5);


System.out.println(s2);
System.out.println("Area is " + s2.getArea());

// Cannot create instance of an abstract class


Shape s3 = new Shape("green"); // Compilation Error!!
}
}

In summary, an abstract class provides a template for further development. The purpose of an
abstract class is to provide a common interface (or protocol, or contract, or understanding, or
naming convention) to all its subclasses. For example, in the abstract class Shape, you can
define abstract methods such as getArea() and draw(). No implementation is possible because
the actual shape is not known. However, by specifying the signature of the abstract methods,
all the subclasses are forced to use these methods' signature. The subclasses could provide the
proper implementations.

Coupled with polymorphism, you can upcast subclass instances to Shape, and program at the
Shape level, i,e., program at the interface. The separation of interface and implementation
enables better software design, and ease in expansion. For example, Shape defines a method
called getArea(), which all the subclasses must provide the correct implementation. You can
ask for a getArea() from any subclasses of Shape, the correct area will be computed.
Furthermore, you application can be extended easily to accommodate new shapes (such as
Circle or Square) by deriving more subclasses.
Rule of Thumb: Program at the interface, not at the implementation. (That is, make references
at the superclass; substitute with subclass instances; and invoke methods defined in the
superclass only.)

Interfaces:

An interface declaration consists of modifiers, the keyword interface, the interface name, a
comma-separated list of parent interfaces (if any), and the interface body. For example:

public interface GroupedInterface extends Interface1, Interface2, Interface3


{

// constant declarations

// base of natural logarithms


double E = 2.718282;

// method signatures
void doSomething (int i, double x);
int doSomethingElse(String s);
}

The public access specifier indicates that the interface can be used by any class in any package.
If you do not specify that the interface is public, your interface will be accessible only to classes
defined in the same package as the interface.

An interface can extend other interfaces, just as a class can extend or subclass another class.
However, whereas a class can extend only one other class, an interface can extend any number of
interfaces. The interface declaration includes a comma-separated list of all the interfaces that it
extends.

Implementing an Interface
To declare a class that implements an interface, you include an implements clause in the class
declaration. Your class can implement more than one interface, so the implements keyword is
followed by a comma-separated list of the interfaces implemented by the class. By convention,
the implements clause follows the extends clause, if there is one.

A Sample Interface, Relatable

Consider an interface that defines how to compare the size of objects.

public interface Relatable {

// this (object calling isLargerThan)


// and other must be instances of
// the same class returns 1, 0, -1
// if this is greater // than, equal
// to, or less than other
public int isLargerThan(Relatable other);
}

If you want to be able to compare the size of similar objects, no matter what they are, the class
that instantiates them should implement Relatable.

Any class can implement Relatable if there is some way to compare the relative "size" of
objects instantiated from the class. For strings, it could be number of characters; for books, it
could be number of pages; for students, it could be weight; and so forth. For planar geometric
objects, area would be a good choice (see the RectanglePlus class that follows), while volume
would work for three-dimensional geometric objects. All such classes can implement the
isLargerThan() method.

If you know that a class implements Relatable, then you know that you can compare the size of
the objects instantiated from that class.

Implementing the Relatable Interface

Here is the Rectangle class that was presented in the Creating Objects section, rewritten to
implement Relatable.

public class RectanglePlus


implements Relatable {
public int width = 0;
public int height = 0;
public Point origin;

// four constructors
public RectanglePlus() {
origin = new Point(0, 0);
}
public RectanglePlus(Point p) {
origin = p;
}
public RectanglePlus(int w, int h) {
origin = new Point(0, 0);
width = w;
height = h;
}
public RectanglePlus(Point p, int w, int h) {
origin = p;
width = w;
height = h;
}

// a method for moving the rectangle


public void move(int x, int y) {
origin.x = x;
origin.y = y;
}

// a method for computing


// the area of the rectangle
public int getArea() {
return width * height;
}

// a method required to implement


// the Relatable interface
public int isLargerThan(Relatable other) {
RectanglePlus otherRect
= (RectanglePlus)other;
if (this.getArea() < otherRect.getArea())
return -1;
else if (this.getArea() > otherRect.getArea())
return 1;
else
return 0;
}

The Interface Body

The interface body contains method declarations for all the methods included in the interface. A
method declaration within an interface is followed by a semicolon, but no braces, because an
interface does not provide implementations for the methods declared within it. All methods
declared in an interface are implicitly public, so the public modifier can be omitted.

An interface can contain constant declarations in addition to method declarations. All constant
values defined in an interface are implicitly public, static, and final. Once again, these
modifiers can be omitted.In Java, an interface is a pure abstract class. An interface contains
only abstract methods (methods with signature and no implementation) and possibly constants
(public static final variables). You have to use the keyword "interface" to define an
interface (instead of keyword "class" for normal classes). The keyword abstract is not
needed for its abstract methods as it is implied.

For example, suppose that our application involves many objects that can move. We could define
an interface called movable, containing the signatures of the various movement methods.

public interface Movable {


// abstract methods to be implemented by the subclasses
public void moveUp();
public void moveDown();
public void moveLeft();
public void moveRight();
}

Similar to an abstract class, an interface cannot be instantiated; because it is incomplete (the


abstract methods' body is missing). To use an interface, again, you must derive subclasses and
provide implementation to all the abstract methods declared in the interface. The subclasses are
now complete and can be instantiated.
To derive subclasses from an interface, a new keyboard "implements" is to be used instead of
"extends" for deriving subclasses from an ordinary class or an abstract class. It is important to
note that the subclass implementing an interface need to override ALL the abstract methods
defined in the interface; otherwise, the subclass cannot be compiled. For example,

public class MovablePoint implements Movable {


// Instance variables - (x, y) coordinates of the point
private int x;
private int y;

// Constructor
public MovablePoint(int x, int y) {
this.x = x;
this.y = y;
}

public String toString() {


return "Point at (" + x + "," + y + ")";
}

// Implement abstract methods defined in the interface Movable


@Override
public void moveUp() {
y--;
}

@Override
public void moveDown() {
y++;
}

@Override
public void moveLeft() {
x--;
}

@Override
public void moveRight() {
x++;
}
}

Other classes in the application can similarly implement the Movable interface and provide their
own implementation to the abstract methods defined in the interface Movable.

We can also upcast subclass instances to the Movable interface, via polymorphism, similar to an
abstract class.

public class TestMovable {


public static void main(String[] args) {
Movable m1 = new MovablePoint(5, 5); // upcast
System.out.println(m1);
m1.moveDown();
System.out.println(m1);
m1.moveRight();
System.out.println(m1);
}
}

The UML notation uses a solid-line arrow linking the subclass to a concrete or abstract
superclass, and dashed-line arrow to an interface as illustrated. Abstract class and abstract
method are shown in italics. For example,

Implementing Multiple Interfaces

As mentioned, Java supports only single inheritance. That is, a subclass can be derived from one
and only one superclass. Java does not support multiple inheritance to avoid inheriting
conflicting properties from multiple superclasses. Multiple inheritance, however, does have its
place in programming.

A subclass, however, can implement more than one interfaces. This is permitted in Java as an
interface merely defines the abstract methods without the actual implementations and less likely
leads to inheriting conflicting properties from multiple interfaces. In other words, Java indirectly
supports multiple inheritances via implementing multiple interfaces. For example,

public class Circle extends Shape implements Movable, Displayable { // One


superclass but implement multiple interfaces
.......
}

Interface Formal Syntax

The formal syntax for declaring interface is:

[public|protected|package] interface interfaceName


[extends superInterfaceName] {
// constants
static final ...;

// abstract methods' signature


...
}

Using an Interface as a Type


When you define a new interface, you are defining a new reference data type. You can use
interface names anywhere you can use any other data type name. If you define a reference
variable whose type is an interface, any object you assign to it must be an instance of a class that
implements the interface.

As an example, here is a method for finding the largest object in a pair of objects, for any objects
that are instantiated from a class that implements Relatable:

public Object findLargest(Object object1, Object object2) {


Relatable obj1 = (Relatable)object1;
Relatable obj2 = (Relatable)object2;
if ((obj1).isLargerThan(obj2) > 0)
return object1;
else
return object2;
}

By casting object1 to a Relatable type, it can invoke the isLargerThan method.

If you make a point of implementing Relatable in a wide variety of classes, the objects
instantiated from any of those classes can be compared with the findLargest() method—
provided that both objects are of the same class. Similarly, they can all be compared with the
following methods:

public Object findSmallest(Object object1, Object object2) {


Relatable obj1 = (Relatable)object1;
Relatable obj2 = (Relatable)object2;
if ((obj1).isLargerThan(obj2) < 0)
return object1;
else
return object2;
}
public boolean isEqual(Object object1, Object object2) {
Relatable obj1 = (Relatable)object1;
Relatable obj2 = (Relatable)object2;
if ( (obj1).isLargerThan(obj2) == 0)
return true;
else
return false;
}

These methods work for any "relatable" objects, no matter what their class inheritance is. When
they implement Relatable, they can be of both their own class (or superclass) type and a
Relatable type. This gives them some of the advantages of multiple inheritance, where they can
have behavior from both a superclass and an interface.

Rewriting Interfaces
Consider an interface that you have developed called DoIt:

public interface DoIt {


void doSomething(int i, double x);
int doSomethingElse(String s);
}

Suppose that, at a later time, you want to add a third method to DoIt, so that the interface now
becomes:

public interface DoIt {

void doSomething(int i, double x);


int doSomethingElse(String s);
boolean didItWork(int i, double x, String s);

If you make this change, all classes that implement the old DoIt interface will break because
they don't implement the interface anymore. Programmers relying on this interface will protest
loudly.

Try to anticipate all uses for your interface and to specify it completely from the beginning.
Given that this is often impossible, you may need to create more interfaces later. For example,
you could create a DoItPlus interface that extends DoIt:

public interface DoItPlus extends DoIt {

boolean didItWork(int i, double x, String s);

Now users of your code can choose to continue to use the old interface or to upgrade to the new
interface.
An interface defines a protocol of communication between two objects.

An interface declaration contains signatures, but no implementations, for a set of methods, and
might also contain constant definitions.

A class that implements an interface must implement all the methods declared in the interface.

An interface name can be used anywhere a type can be used

Why interface?

An interface is a contract (or a protocol, or a common understanding), which consists of a set of


abstract methods. When a class implements a certain interface, it promises to provide
implementation to all the abstract methods declared in the interface. Interface defines a set of
common behaviors. The classes implement the interface agree to these behaviors and provide
their own implementation to the behaviors. This allows you to program at the interface, instead
of the actual implementation.

Secondly, Java does not support multiple inheritance (whereas C++ does). Multiple inheritance
permits you to derive a subclass from more than one direct superclass. This poses a problem if
two direct superclasses have conflicting implementations. (Which one to follow in the
subclass?). However, multiple inheritance does have its place. Java does this by permitting you
to "implements" more than one interfaces (but you can only "extends" from a single superclass).
Since interfaces contain only abstract methods without actual implementation, no conflict can
arise among the multiple interfaces. (Interface can hold constants but is not recommended. If a
subclass implements two interfaces with conflicting constants, the compiler will flag out a
compilation error.)

The UML notation uses a solid-line arrow linking the subclass to a concrete or abstract
superclass, and dashed-line arrow to an interface as illustrated. Abstract class and abstract
method are shown in italics.

Dynamic Binding

We often treat an object not as its own type, but as its base type (superclass or interface). This
allows you to write codes that do not depends on a specific implementation type. In the Shape
example, we can always use getArea() and do not have to worry whether they are triangles or
circles.

this, however, poses a new problem. The compiler cannot know at compile time precisely which
piece of codes is going to be executed at run-time (e.g., getArea() has different implementation
for Rectangle and Triangle).

In the procedural language like C, the compiler generates a call to a specific function name, and
the linkage editor resolves this call to the absolute address of the code to be executed at run-time.
This mechanism is called static binding.

To support polymorphism, object-oriented language uses a different mechanism called dynamic


binding (or late-binding or run-time binding). When a method is invoked, the code to be
executed is only determined at run-time. During the compilation, the compiler checks whether
the method exists and performs type check on the arguments and return type, but does not know
which piece of codes to execute at run-time. When a message is sent to an object to invoke a
method, the object figures out which piece of codes to execute at run-time.

Although dynamic binding resolves the problem in supporting polymorphism, it poses another
new problem. The compiler is unable to check whether the type casting operator is safe. JDK 1.5
introduces a new feature called generics to tackle this issue. We shall discuss this problem and
generics in details in the later chapter.

dynamic Binding or Late Binding


Dynamic Binding refers to the case where compiler is not able to resolve the call and the binding
is done at runtime only. Let's try to understand this. Suppose we have a class named 'SuperClass'
and another class named 'SubClass' extends it. Now a 'SuperClass' reference can be assigned to
an object of the type 'SubClass' as well. If we have a method (say 'someMethod()') in the
'SuperClass' which we override in the 'SubClass' then a call of that method on a 'SuperClass'
reference can only be resolved at runtime as the compiler can't be sure of what type of object this
reference would be pointing to at runtime.

...
SuperClass superClass1 = new SuperClass();
SuperClass superClass2 = new SubClass();
...

superClass1.someMethod(); // SuperClass version is called


superClass2.someMethod(); // SubClass version is called
....

Here, we see that even though both the object references superClass1 and superClass2 are of type
'SuperClass' only, but at run time they refer to the objects of types 'SuperClass' and 'SubClass'
respectively.

Hence, at compile time the compiler can't be sure if the call to the method 'someMethod()' on
these references actually refer to which version of the method - the super class version or the sub
class version.

Thus, we see that dynamic binding in Java simply binds the method calls (inherited methods only
as they can be overriden in a sub class and hence compiler may not be sure of which version of
the method to call) based on the actual object type and not on the declared type of the object
reference.

Static Binding or Early Binding

If the compiler can resolve the binding at the compile time only then such a binding is called
Static Binding or Early Binding. All the instance method calls are always resolved at runtime,
but all the static method calls are resolved at compile time itself and hence we have static
binding for static method calls. Because static methods are class methods and hence they can be
accessed using the class name itself (in fact they are encourgaed to be used using their
corresponding class names only and not by using the object references) and therefore access to
them is required to be resolved during compile time only using the compile time type
information. That's the reason why static methods can not actually be overriden. Read more -
Can you override static methods in Java?

Similarly, access to all the member variables in Java follows static binding as Java doesn't
support (in fact, it discourages) polymorphic behavior of member variables. For example:-

class SuperClass{
...
public String someVariable = "Some Variable in SuperClass";
...
}

class SubClass extends SuperClass{


...
public String someVariable = "Some Variable in SubClass";
...
}
...
...

SuperClass superClass1 = new SuperClass();


SuperClass superClass2 = new SubClass();

System.out.println(superClass1.someVariable);
System.out.println(superClass2.someVariable);
...

Output:-
Some Variable in SuperClass
Some Variable in SuperClass

We can observe that in both the cases, the member variable is resolved based on the
declared type of the object reference only, which the compiler is capable of finding
as early as at the compile time only and hence a static binding in this case. Another
example of static binding is that of 'private' methods as they are never inherited
and the compile can resolve calls to any private method at compile time only.

Late Binding Vs. Static Binding

November 23, 2007 by onlyjava

Dynamic binding and static binding have to do with inheritance. In Java, any derived class
object can be assigned to a base class variable. For instance, if you have a class named Animal
from which you derived the class Dog, you can do this:

Animal myAnimal = new Dog();

The variable on the left is type Animal, but the object on the right is type Dog. As long as the
variable on the left is a base class of Dog, you are allowed to do that. Being able to do
assignments like that sets up what is called “polymorphic behavior”: if the Dog class has a
method that is the same as a method in the Animal class, then the version of the method in the
Dog class will be called. For instance, if both classes define a method called show(), and you do
this:

myAnimal.show();
the version of show() in the Dog class will be called. Even though you are using an Animal
variable type to call the method show(), the version of show() in the Animal class won’t be
executed. Instead, it is the version of show() in the Dog class that will be executed. The type of
the object that is assigned to the Animal variable determines the method that is called.

So, when the compiler scans the program and sees a statement like this:

myAnimal.show();

it knows that myAnimal is of type Animal, but the compiler also knows that myAnimal can be a
reference to any class derived from Animal. Therefore, the compiler doesn’t know what version
of show() that statement is calling. It’s not until the assignment:

Animal myAnimal = new Dog();

is executed that the version of show() is determined. Since the assignment doesn’t occur until
runtime, it’s not until runtime that the correct version of show() is known. That is known as
“dynamic binding” or “late binding”: it’s not until your program performs some operation at
runtime that the correct version of a method can be determined. In Java, most uses of inheritance
involve dynamic binding.

“Static binding” or “early binding” occurs when the compiler can readily determine the correct
version of something during compile time, i.e. before the program is executed. In Java, member
variables have static binding because Java does not allow for polymorphic behavior with
member variables. That means if both the Animal class and the Dog class have a member
variable with the same name, it’s the base class version that is used. For instance, if you set up
the necessary ingredients for polymorphic behavior:

Animal myAnimal = new Dog();

and both the Animal and Dog classes have a String member variable ‘type’, then if you do this:

String str = myAnimal.type;

the value of ‘type’ can be fully determined by the compiler. Because polymorphic behavior is not
allowed for member variables, that statement is referring to the value of ‘type’ in the Animal
class–not the Dog’s value for ‘type’. The result is: with member variables, it’s the type of the
variable(e.g. myAnimal) that determines which version is called–not the type of the object the
variable refers to(e.g. Dog). When the compiler is able to figure out the correct version of
something during compilation, that’s known as static binding.

Here is an example of both dynamic and static binding:

class Animal
{
public String type = "mammal";
public void show()
{
System.out.println("The animal is a: " + type);
}
}

class Dog extends Animal


{
public String type; //same member variable name as in base class

public Dog(String type)


{
this.type = type;
}

public void show() //same method signature as in base class


{
System.out.println("The dog is a: " + type);
}
}

public class DemoStaticBinding


{
public static void main(String[] args)
{
Animal doggie = new Dog("daschund");
doggie.show(); // "The dog is a: daschund" (dynamic binding)
System.out.println("The type is: " + doggie.type); //"The type
is: mammal" (static binding)
}
}

Dynamic method dispatch:


While the examples in the preceding section demonstrate the mechanics of method overriding,
they do not show its power. Indeed, if there were nothing more to method overriding than a name
space convention, then it would be, at best, an interesting curiosity, but of little real value.
However, this is not the case. Method overriding forms the basis for one of Java's most powerful
concepts: dynamic method dispatch.

Dynamic method dispatch is the mechanism by which a call to an overridden method is


resolved at run time, rather than compile time. Dynamic method dispatch is important because
this is how Java implements run-time polymorphism. Let's begin by restating an important
principle: a superclass reference variable can refer to a subclass object.

Java uses this fact to resolve calls to overridden methods at run time. Here is how. When
an overridden method is called through a superclass reference, Java determines which version of
that method to execute based upon the type of the object being referred to at the time the call
occurs. Thus, this determination is made at run time. When different types of objects are referred
to, different versions of an overridden method will be called.
In other words, it is the type of the object being referred to (not the type of the reference
variable) that determines which version of an overridden method will be executed. Therefore, if a
superclass contains a method that is overridden by a subclass, then when different types of
objects are referred to through a superclass reference variable, different versions of the method
are executed.

Here is an example that illustrates dynamic method dispatch:

// Dynamic Method Dispatch


class A {
void callme() {
System.out.println("Inside A's callme method");
}
}
class B extends A {
// override callme()
void callme() {
System.out.println("Inside B's callme method");
}
}
class C extends A {
// override callme()
void callme() {
System.out.println("Inside C's callme method");
}
}
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}

The output from the program is shown here:

Inside A's callme method


Inside B's callme method
Inside C's callme method

This program creates one superclass called A and two subclasses of it, called B and C.
Subclasses B and C override callme( ) declared in A. Inside the main( ) method, objects of type
A, B, and C are declared. Also, a reference of type A, called r, is declared.

The program then assigns a reference to each type of object to r and uses that reference to invoke
callme( ). As the output shows, the version of callme( ) executed is determined by the type of
object being referred to at the time of the call. Had it been determined by the type of the
reference variable, r, you would see three calls to A's callme( ) method.

Readers familiar with C++ or C# will recognize that overridden methods in Java are similar to
virtual functions in those languages.

In dynamic method dispatch,super class refers to subclass object and implements method
overriding.
Example:

class Flower {
void which() {
System.out.println("A Beautiful flower.");
}
}
class Rose extends Flower {
void which() {
System.out.println("Rose");
}
}
class Lotus extends Flower {
void which() {
System.out.println("Lotus.");
}
}
class Test {

public static void main(String[] args) {


Flower ref1 = new Flower();
Flower ref2 = new Rose();
Flower ref3 = new Lotus();
ref1.which();
ref2.which();
ref3.which();
}
}
Strings
Strings, which are widely used in Java programming, are a sequence of characters. In the Java
programming language, strings are objects.

The Java platform provides the String class to create and manipulate strings.

Creating Strings

The most direct way to create a string is to write:

String greeting = "Hello world!";

In this case, "Hello world!" is a string literal—a series of characters in your code that is enclosed
in double quotes. Whenever it encounters a string literal in your code, the compiler creates a
String object with its value—in this case, Hello world!.

As with any other object, you can create String objects by using the new keyword and a
constructor. The String class has thirteen constructors that allow you to provide the initial
value of the string using different sources, such as an array of characters:

char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };


String helloString = new String(helloArray);
System.out.println(helloString);

The last line of this code snippet displays hello.

Note: The String class is immutable, so that once it is created a String object cannot be
changed. The String class has a number of methods, some of which will be discussed below,
that appear to modify strings. Since strings are immutable, what these methods really do is
create and return a new string that contains the result of the operation.

String Length

Methods used to obtain information about an object are known as accessor methods. One
accessor method that you can use with strings is the length() method, which returns the
number of characters contained in the string object. After the following two lines of code have
been executed, len equals 17:

String palindrome = "Dot saw I was Tod";


int len = palindrome.length();

A palindrome is a word or sentence that is symmetric—it is spelled the same forward and
backward, ignoring case and punctuation. Here is a short and inefficient program to reverse a
palindrome string. It invokes the String method charAt(i), which returns the ith character
in the string, counting from 0.

public class StringDemo {


public static void main(String[] args) {
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
char[] tempCharArray = new char[len];
char[] charArray = new char[len];

// put original string in an


// array of chars
for (int i = 0; i < len; i++) {
tempCharArray[i] =
palindrome.charAt(i);
}

// reverse array of chars


for (int j = 0; j < len; j++) {
charArray[j] =
tempCharArray[len - 1 - j];
}

String reversePalindrome =
new String(charArray);
System.out.println(reversePalindrome);
}
}

Running the program produces this output:

doT saw I was toD

To accomplish the string reversal, the program had to convert the string to an array of characters
(first for loop), reverse the array into a second array (second for loop), and then convert back
to a string. The String class includes a method, getChars(), to convert a string, or a
portion of a string, into an array of characters so we could replace the first for loop in the
program above with

palindrome.getChars(0, len, tempCharArray, 0);


Concatenating Strings

The String class includes a method for concatenating two strings:

string1.concat(string2);

This returns a new string that is string1 with string2 added to it at the end.

You can also use the concat() method with string literals, as in:

"My name is ".concat("Rumplestiltskin");

Strings are more commonly concatenated with the + operator, as in

"Hello," + " world" + "!"

which results in

"Hello, world!"

The + operator is widely used in print statements. For example:

String string1 = "saw I was ";


System.out.println("Dot " + string1 + "Tod");

which prints

Dot saw I was Tod

Such a concatenation can be a mixture of any objects. For each object that is not a String, its
toString() method is called to convert it to a String.

Note: The Java programming language does not permit literal strings to span lines in source
files, so you must use the + concatenation operator at the end of each line in a multi-line string.
For example:

String quote =
"Now is the time for all good " +
"men to come to the aid of their country.";

Breaking strings between lines using the + concatenation operator is, once again, very common
in print statements.
Creating Format Strings

You have seen the use of the printf() and format() methods to print output with
formatted numbers. The String class has an equivalent class method, format(), that returns
a String object rather than a PrintStream object.

Using String's static format() method allows you to create a formatted string that you can
reuse, as opposed to a one-time print statement. For example, instead of

System.out.printf("The value of the float " +


"variable is %f, while " +
"the value of the " +
"integer variable is %d, " +
"and the string is %s",
floatVar, intVar, stringVar);

you can write

String fs;
fs = String.format("The value of the float " +
"variable is %f, while " +
"the value of the " +
"integer variable is %d, " +
" and the string is %s",
floatVar, intVar, stringVar);
System.out.println(fs);

Converting Between Numbers and Strings


Converting Strings to Numbers

Frequently, a program ends up with numeric data in a string object—a value entered by the user,
for example.

The Number subclasses that wrap primitive numeric types ( Byte, Integer, Double, Float,
Long, and Short) each provide a class method named valueOf that converts a string to an object
of that type. Here is an example, ValueOfDemo , that gets two strings from the command line,
converts them to numbers, and performs arithmetic operations on the values:

public class ValueOfDemo {


public static void main(String[] args) {
// this program requires two
// arguments on the command line
if (args.length == 2) {
// convert strings to numbers
float a = (Float.valueOf(args[0])).floatValue();
float b = (Float.valueOf(args[1])).floatValue();

// do some arithmetic
System.out.println("a + b = " +
(a + b));
System.out.println("a - b = " +
(a - b));
System.out.println("a * b = " +
(a * b));
System.out.println("a / b = " +
(a / b));
System.out.println("a % b = " +
(a % b));
} else {
System.out.println("This program " +
"requires two command-line arguments.");
}
}
}

The following is the output from the program when you use 4.5 and 87.2 for the command-
line arguments:

a + b = 91.7
a - b = -82.7
a * b = 392.4
a / b = 0.0516055
a % b = 4.5

Note: Each of the Number subclasses that wrap primitive numeric types also provides a parseXXXX()
method (for example, parseFloat()) that can be used to convert strings to primitive numbers. Since a
primitive type is returned instead of an object, the parseFloat() method is more direct than the
valueOf() method. For example, in the ValueOfDemo program, we could use:

float a = Float.parseFloat(args[0]);
float b = Float.parseFloat(args[1]);
Converting Numbers to Strings

Sometimes you need to convert a number to a string because you need to operate on the value in
its string form. There are several easy ways to convert a number to a string:

int i;
// Concatenate "i" with an empty string; conversion is handled for you.
String s1 = "" + i;

or

// The valueOf class method.


String s2 = String.valueOf(i);

Each of the Number subclasses includes a class method, toString(), that will convert its
primitive type to a string. For example:

int i;
double d;
String s3 = Integer.toString(i);
String s4 = Double.toString(d);

The ToStringDemo example uses the toString method to convert a number to a string. The
program then uses some string methods to compute the number of digits before and after the
decimal point:

public class ToStringDemo {

public static void main(String[] args) {


double d = 858.48;
String s = Double.toString(d);

int dot = s.indexOf('.');

System.out.println(dot + " digits " +


"before decimal point.");
System.out.println( (s.length() - dot - 1) +
" digits after decimal point.");
}
}

The output of this program is:

3 digits before decimal point.


2 digits after decimal point.
Manipulating Characters in a String
The String class has a number of methods for examining the contents of strings, finding
characters or substrings within a string, changing case, and other tasks.

Getting Characters and Substrings by Index

You can get the character at a particular index within a string by invoking the charAt() accessor
method. The index of the first character is 0, while the index of the last character is length()-1.
For example, the following code gets the character at index 9 in a string:

String anotherPalindrome = "Niagara. O roar again!";


char aChar = anotherPalindrome.charAt(9);

Indices begin at 0, so the character at index 9 is 'O', as illustrated in the following figure:

If you want to get more than one consecutive character from a string, you can use the substring
method. The substring method has two versions, as shown in the following table:

The substring Methods in the String Class

Method Description

Returns a new string that is a substring of this string. The first


String substring(int integer argument specifies the index of the first character.
beginIndex, int endIndex) The second integer argument is the index of the last
character - 1.

Returns a new string that is a substring of this string. The


String substring(int integer argument specifies the index of the first character.
beginIndex) Here, the returned substring extends to the end of the
original string.

The following code gets from the Niagara palindrome the substring that extends from index 11
up to, but not including, index 15, which is the word "roar":
String anotherPalindrome = "Niagara. O roar again!";
String roar = anotherPalindrome.substring(11, 15);

Other Methods for Manipulating Strings

Here are several other String methods for manipulating strings:

Other Methods in the String Class for Manipulating Strings

Method Description

Searches for a match as specified by the string


argument (which contains a regular expression)
String[] split(String regex) and splits this string into an array of strings
String[] split(String regex, int accordingly. The optional integer argument
limit) specifies the maximum size of the returned array.
Regular expressions are covered in the lesson
titled "Regular Expressions."

CharSequence subSequence(int Returns a new character sequence constructed


beginIndex, int endIndex) from beginIndex index up until endIndex - 1.

Returns a copy of this string with leading and


String trim()
trailing white space removed.

Returns a copy of this string converted to


String toLowerCase() lowercase or uppercase. If no conversions are
String toUpperCase() necessary, these methods return the original
string.

Searching for Characters and Substrings in a String

Here are some other String methods for finding characters or substrings within a string. The
String class provides accessor methods that return the position within the string of a specific
character or substring: indexOf() and lastIndexOf(). The indexOf() methods search forward
from the beginning of the string, and the lastIndexOf() methods search backward from the end
of the string. If a character or substring is not found, indexOf() and lastIndexOf() return -1.

The String class also provides a search method, contains, that returns true if the string
contains a particular character sequence. Use this method when you only need to know that the
string contains a character sequence, but the precise location isn't important.

The following table describes the various string search methods.

The Search Methods in the String Class

Method Description

int indexOf(int ch) Returns the index of the first (last) occurrence of
int lastIndexOf(int ch) the specified character.

Returns the index of the first (last) occurrence of


int indexOf(int ch, int fromIndex)
the specified character, searching forward
int lastIndexOf(int ch, int fromIndex)
(backward) from the specified index.

int indexOf(String str) Returns the index of the first (last) occurrence of
int lastIndexOf(String str) the specified substring.

int indexOf(String str, int fromIndex) Returns the index of the first (last) occurrence of
int lastIndexOf(String str, int the specified substring, searching forward
fromIndex) (backward) from the specified index.

Returns true if the string contains the specified


boolean contains(CharSequence s)
character sequence.

Note: CharSequence is an interface that is implemented by the String class. Therefore, you can use a
string as an argument for the contains() method.

Replacing Characters and Substrings into a String

The String class has very few methods for inserting characters or substrings into a string. In
general, they are not needed: You can create a new string by concatenation of substrings you
have removed from a string with the substring that you want to insert.
The String class does have four methods for replacing found characters or substrings, however.
They are:

Methods in the String Class for Manipulating Strings

Method Description

String replace(char oldChar, char Returns a new string resulting from replacing all
newChar) occurrences of oldChar in this string with newChar.

Replaces each substring of this string that matches


String replace(CharSequence target,
the literal target sequence with the specified
CharSequence replacement)
literal replacement sequence.

Replaces each substring of this string that matches


String replaceAll(String regex, String
the given regular expression with the given
replacement)
replacement.

Replaces the first substring of this string that


String replaceFirst(String regex,
matches the given regular expression with the
String replacement)
given replacement.

An Example

The following class, Filename, illustrates the use of lastIndexOf() and substring() to isolate
different parts of a file name.

Note: The methods in the following Filename class don't do any error checking and assume that their
argument contains a full directory path and a filename with an extension. If these methods were
production code, they would verify that their arguments were properly constructed.

public class Filename {


private String fullPath;
private char pathSeparator,
extensionSeparator;

public Filename(String str, char sep, char ext) {


fullPath = str;
pathSeparator = sep;
extensionSeparator = ext;
}

public String extension() {


int dot = fullPath.lastIndexOf(extensionSeparator);
return fullPath.substring(dot + 1);
}

// gets filename without extension


public String filename() {
int dot = fullPath.lastIndexOf(extensionSeparator);
int sep = fullPath.lastIndexOf(pathSeparator);
return fullPath.substring(sep + 1, dot);
}

public String path() {


int sep = fullPath.lastIndexOf(pathSeparator);
return fullPath.substring(0, sep);
}
}

Here is a program, FilenameDemo, that constructs a Filename object and calls all of its
methods:

public class FilenameDemo {


public static void main(String[] args) {
final String FPATH = "/home/user/index.html";
Filename myHomePage = new Filename(FPATH, '/', '.');
System.out.println("Extension = " +
myHomePage.extension());
System.out.println("Filename = " +
myHomePage.filename());
System.out.println("Path = " + myHomePage.path());
}
}

And here's the output from the program:

Extension = html
Filename = index
Path = /home/mem

As shown in the following figure, our extension method uses lastIndexOf to locate the
last occurrence of the period (.) in the file name. Then substring uses the return value of
lastIndexOf to extract the file name extension — that is, the substring from the period to the
end of the string. This code assumes that the file name has a period in it; if the file name does not
have a period, lastIndexOf returns -1, and the substring method throws a
StringIndexOutOfBoundsException.

Comparing Strings and Portions of Strings

The String class has a number of methods for comparing strings and portions of strings. The
following table lists these methods.

Methods for Comparing Strings


Method Description
Returns true if this string ends with or begins
boolean endsWith(String suffix)
boolean startsWith(String prefix) with the substring specified as an argument to
the method.
Considers the string beginning at the index
boolean startsWith(String prefix, int
offset) offset, and returns true if it begins with the
substring specified as an argument.
Compares two strings lexicographically.
Returns an integer indicating whether this
int compareTo(String anotherString) string is greater than (result is > 0), equal to
(result is = 0), or less than (result is < 0) the
argument.
Compares two strings lexicographically,
ignoring differences in case. Returns an integer
int compareToIgnoreCase(String str) indicating whether this string is greater than
(result is > 0), equal to (result is = 0), or less
than (result is < 0) the argument.

Returns true if and only if the argument is a


boolean equals(Object anObject) String object that represents the same
sequence of characters as this object.

Returns true if and only if the argument is a


boolean equalsIgnoreCase(String String object that represents the same
anotherString) sequence of characters as this object, ignoring
differences in case.
Tests whether the specified region of this string
boolean regionMatches(int toffset,
String other, int ooffset, int len) matches the specified region of the String
argument.
Region is of length len and begins at the index
toffset for this string and ooffset for the
other string.
Tests whether the specified region of this string
matches the specified region of the String
argument.

boolean regionMatches(boolean Region is of length len and begins at the index


ignoreCase, int toffset, String other, toffset for this string and ooffset for the
int ooffset, int len) other string.

The boolean argument indicates whether case


should be ignored; if true, case is ignored when
comparing characters.
Tests whether this string matches the specified
boolean matches(String regex)
regular expression. Regular expressions are
discussed in the lesson titled "Regular
Expressions."

The following program, RegionMatchesDemo, uses the regionMatches method to search


for a string within another string:

public class RegionMatchesDemo {


public static void main(String[] args) {
String searchMe = "Green Eggs and Ham";
String findMe = "Eggs";
int searchMeLength = searchMe.length();
int findMeLength = findMe.length();
boolean foundIt = false;
for (int i = 0;
i <= (searchMeLength - findMeLength);
i++) {
if (searchMe.regionMatches(i, findMe, 0,
findMeLength)) {
foundIt = true;
System.out.println(searchMe.substring(i, i +
findMeLength));
break;
}
}
if (!foundIt)
System.out.println("No match found.");
}
}

The output from this program is Eggs.

The program steps through the string referred to by searchMe one character at a time. For each
character, the program calls the regionMatches method to determine whether the substring
beginning with the current character matches the string the program is looking for.

The StringBuilder Class


StringBuilder objects are like String objects, except that they can be modified. Internally,
these objects are treated like variable-length arrays that contain a sequence of characters. At any
point, the length and content of the sequence can be changed through method invocations.

Strings should always be used unless string builders offer an advantage in terms of simpler code
(see the sample program at the end of this section) or better performance. For example, if you
need to concatenate a large number of strings, appending to a StringBuilder object is more
efficient.

Length and Capacity

The StringBuilder class, like the String class, has a length() method that returns the
length of the character sequence in the builder.

Unlike strings, every string builder also has a capacity, the number of character spaces that have
been allocated. The capacity, which is returned by the capacity() method, is always greater
than or equal to the length (usually greater than) and will automatically expand as necessary to
accommodate additions to the string builder.

StringBuilder Constructors

Constructor Description

Creates an empty string builder with a capacity of


StringBuilder()
16 (16 empty elements).

Constructs a string builder containing the same


characters as the specified CharSequence, plus
StringBuilder(CharSequence cs)
an extra 16 empty elements trailing the
CharSequence.
Creates an empty string builder with the specified
StringBuilder(int initCapacity)
initial capacity.

Creates a string builder whose value is initialized


StringBuilder(String s) by the specified string, plus an extra 16 empty
elements trailing the string.

For example, the following code

// creates empty builder, capacity 16


StringBuilder sb = new StringBuilder();
// adds 9 character string at beginning
sb.append("Greetings");

will produce a string builder with a length of 9 and a capacity of 16:

The StringBuilder class has some methods related to length and capacity that the String class
does not have:

Length and Capacity Methods

Method Description

Sets the length of the character sequence. If


newLength is less than length(), the last
characters in the character sequence are
void setLength(int newLength)
truncated. If newLength is greater than
length(), null characters are added at the end of
the character sequence.

Ensures that the capacity is at least equal to the


void ensureCapacity(int minCapacity)
specified minimum.
A number of operations (for example, append(), insert(), or setLength()) can increase the
length of the character sequence in the string builder so that the resultant length() would be
greater than the current capacity(). When this happens, the capacity is automatically increased.

StringBuilder Operations

The principal operations on a StringBuilder that are not available in String are the
append() and insert() methods, which are overloaded so as to accept data of any type.
Each converts its argument to a string and then appends or inserts the characters of that string to
the character sequence in the string builder. The append method always adds these characters at
the end of the existing character sequence, while the insert method adds the characters at a
specified point.

Here are a number of the methods of the StringBuilder class.

Various StringBuilder Methods

Method Description

StringBuilder append(boolean b)
StringBuilder append(char c)
StringBuilder append(char[]
str)
StringBuilder append(char[]
str, int offset, int len) Appends the argument to this string builder.
StringBuilder append(double d) The data is converted to a string before the
StringBuilder append(float f) append operation takes place.
StringBuilder append(int i)
StringBuilder append(long lng)
StringBuilder append(Object
obj)
StringBuilder append(String s)

The first method deletes the subsequence


StringBuilder delete(int start,
from start to end-1 (inclusive) in the
int end)
StringBuilder's char sequence. The
StringBuilder deleteCharAt(int
second method deletes the character located
index)
at index.

StringBuilder insert(int Inserts the second argument into the string


offset, boolean b) builder. The first integer argument indicates
StringBuilder insert(int the index before which the data is to be
offset, char c) inserted. The data is converted to a string
StringBuilder insert(int before the insert operation takes place.
offset, char[] str)
StringBuilder insert(int index,
char[] str, int offset, int
len)
StringBuilder insert(int
offset, double d)
StringBuilder insert(int
offset, float f)
StringBuilder insert(int
offset, int i)
StringBuilder insert(int
offset, long lng)
StringBuilder insert(int
offset, Object obj)
StringBuilder insert(int
offset, String s)

StringBuilder replace(int
start, int end, String s) Replaces the specified character(s) in this
void setCharAt(int index, char string builder.
c)

Reverses the sequence of characters in this


StringBuilder reverse()
string builder.

Returns a string that contains the character


String toString()
sequence in the builder.

Note: You can use any String method on a StringBuilder object by first converting the
string builder to a string with the toString() method of the StringBuilder class. Then
convert the string back into a string builder using the StringBuilder(String str)
constructor.
An Example

The StringDemo program that was listed in the section titled "Strings" is an example of a
program that would be more efficient if a StringBuilder were used instead of a String.

StringDemo reversed a palindrome. Here, once again, is its listing:

public class StringDemo {


public static void main(String[] args) {
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
char[] tempCharArray = new char[len];
char[] charArray = new char[len];

// put original string in an


// array of chars
for (int i = 0; i < len; i++) {
tempCharArray[i] =
palindrome.charAt(i);
}

// reverse array of chars


for (int j = 0; j < len; j++) {
charArray[j] =
tempCharArray[len - 1 - j];
}

String reversePalindrome =
new String(charArray);
System.out.println(reversePalindrome);
}
}

Running the program produces this output:

doT saw I was toD

To accomplish the string reversal, the program converts the string to an array of characters (first
for loop), reverses the array into a second array (second for loop), and then converts back to a
string.

If you convert the palindrome string to a string builder, you can use the reverse() method
in the StringBuilder class. It makes the code simpler and easier to read:
public class StringBuilderDemo {
public static void main(String[] args) {
String palindrome = "Dot saw I was Tod";

StringBuilder sb = new StringBuilder(palindrome);

sb.reverse(); // reverse it

System.out.println(sb);
}
}

Running this program produces the same output:

doT saw I was toD

Note that println() prints a string builder, as in:

System.out.println(sb);

because sb.toString() is called implicitly, as it is with any other object in a println()


invocation.

Note: There is also a StringBuffer class that is exactly the same as the StringBuilder
class, except that it is thread-safe by virtue of having its methods synchronized. Threads will be
discussed in the lesson on concurrency.

ost of the time, if you are using a single character value, you will use the primitive char type.
There are times, however, when you need to use a char as an object—for example, as a method
argument where an object is expected. The Java programming language provides a wrapper class
that "wraps" the char in a Character object for this purpose. An object of type Character
contains a single field whose type is char. This Character class also offers a number of useful
class (i.e., static) methods for manipulating characters.

Strings are a sequence of characters and are widely used in Java programming. In the Java
programming language, strings are objects. The String class has over 60 methods and 13
constructors.

Most commonly, you create a string with a statement like

String s = "Hello world!";

rather than using one of the String constructors.


The String class has many methods to find and retrieve substrings; these can then be easily
reassembled into new strings using the + concatenation operator.

The String class also includes a number of utility methods, among them split(),
toLowerCase(), toUpperCase(), and valueOf(). The latter method is indispensable in
converting user input strings to numbers. The Number subclasses also have methods for
converting strings to numbers and vice versa.

In addition to the String class, there is also a StringBuilder class. Working with
StringBuilder objects can sometimes be more efficient than working with strings. The
StringBuilder class offers a few methods that can be useful for strings, among them
reverse(). In general, however, the String class has a wider variety of methods.

A string can be converted to a string builder using a StringBuilder constructor. A string


builder can be converted to a string with the toString() method.

Java - Math class in Java

In this example you will learn about Math class. This example explains how you can use
functions provided by the Math class like E, PI, round, abs, ceil, exp, floor, IEEEremainder,
max, min, pow, random, rint, sqrt etc. to manipulate the mathematical operation in your program.
The Math class is used to operate the calculations. There is not necessary to import any package
for the Math class because this is already in java.lang package.

Any expressions can be operated through certain method calls. There are some functions have
been used in the given example. All the functions have been explained below with example :

E
This is E field of the Math class which returns you a default exponent value that is closer than
any other to e, the base of the natural logarithms.

PI

This is also a field of the Method class which returns you a default pi value, the ratio of the
circumference of a circle to its diameter.

abs()

This is the abs() function which returns you the absolute number.

ceil()
This is the ceil() function which returns you the smallest value but greater than the argument.

exp()

This is the exp() function which returns you the exponential value raised to the power of a
double value.

floor()

This is the floor() function which returns you the largest value but less than the argument.

IEEEremainder()

This is the IEEEremainder() which returns you the remainder for the given dividend and divisor.

max()

This is the max() function which distinguishes the maximum value from the two given value.

min()

This is the min() function which distinguishes the minimum value from the two given value.

pow()

This is the pow() function which returns you the number raised to the power of a first given
value by the another one.

random()

This is the random() function which returns you the random number. It is absolutely system
generated.

rint()

This is the rint() function which returns you a value closest to the given value.

round()

This is the round() function which returns you a value that is in the rounded form.

sqrt()

This is the sqrt() function which returns you the square root of the specified value.

Code for the program :


public class mathclass{
public static void main(String[] args){
//E and round()
System.out.println("e = " + Math.round(Math.E*100)/100f);
//PI
System.out.println("pi = " + Math.round(Math.PI*100)/100f);
//abs()
System.out.println("Absolute number = " + Math.abs(Math.PI));
//ceil()
System.out.println("Smallest value but greater than

the argument = " + Math.ceil(Math.PI));


//exp()
System.out.println("Exponent number powered by the argument = " + Math.exp(
));
//floor()
System.out.println("Largest value but less

than the argument = " + Math.floor(Math.E));


//IEEEremainder()
System.out.println("Remainder = " +

Math.IEEEremainder(5.3f,2.2f));
//max()
System.out.println("Maximum Number = " +

Math.max(10,10.3));
//min()
System.out.println("Minimum Number = " +

Math.min(10,10.3));
//pow()
System.out.println("Power = " + Math.pow(10,3));
//random()
System.out.println("Random Number = " +

Math.random());
//rint()
System.out.println("Closest to the Argument

= " + Math.rint(30));
//round()
System.out.println("Round = " + Math.round(Math.E));
//sqrt()
System.out.println("Square Root = " + Math.sqrt(400));
}
}

Casting and Converting Objects and Primitive Types

One thing you discover quickly about Java is how finicky it is about the information it will
handle. Like Morris, the perpetually hard-to-please cat in the 9Lives™ Cat Food commercials,
Java expects things to be a certain way and won't put up with alternatives.
When you are sending arguments to methods or using variables in expressions, you must use
variables of the right data types. If a method requires an int, the Java compiler responds with an
error if you try to send a float value to the method. Likewise, if you're setting up one variable
with the value of another, they must be of the same type.

NOTE

There is one area where Java's compiler is decidedly un–Morris-like: Strings. String handling in
println() methods, assignment statements, and method arguments is simplified by the
concatenation operator (+). If any variable in a group of concatenated variables is a string, Java
treats the whole thing as a String. This makes the following possible:

float gpa = 2.25F;


System.out.println("Honest, dad, my GPA is a " + (gpa+1.5));

Sometimes you'll have a value in your Java program that isn't the right type for what you need. It
might be the wrong class or the wrong data type, such as a float when you need an int.

You use casting to convert a value from one type to another.

Casting is the process of producing a new value that has a different type than its source. The
word's meaning is similar to that regarding acting, where a character on a TV show can be recast
with another actor after a salary dispute or an unfortunate public lewdness arrest.

Although the concept of casting is reasonably simple, the usage is complicated by the fact that
Java has both primitive types (such as int, float, and boolean) and object types (String,
Point, ZipFile, and the like). There are three forms of casts and conversions to talk about in
this section:

 Casting between primitive types, such as int to float, or float to double


 Casting from an instance of a class to an instance of another class
 Casting primitive types to objects and then extracting primitive values from those objects

When discussing casting, it can be easier to think in terms of sources and destinations. The
source is the variable being cast into another type. The destination is the result.

Casting Primitive Types

Casting between primitive types enables you to convert the value of one type to another
primitive type. It most commonly occurs with the numeric types, and there's one primitive type
that can never be used in a cast. Boolean values must be either true or false and cannot be used
in a casting operation.

In many casts between primitive types, the destination can hold larger values than the source, so
the value is converted easily. An example would be casting a byte into an int. Because a byte
holds values from –128 to 127 and an int holds from -2.1 billion to 2.1 billion, there's more than
enough room to cast a byte into an int.

You can often automatically use a byte or a char as an int; you can use an int as a long, an
int as a float, or anything as a double. In most cases, because the larger type provides more
precision than the smaller, no loss of information occurs as a result. The exception is casting
integers to floating-point values; casting an int or a long to a float, or a long to a double, can
cause some loss of precision.

NOTE

A character can be used as an int because each character has a corresponding numeric code that
represents its position in the character set. If the variable i has the value 65, the cast (char)i
produces the character value 'A'. The numeric code associated with a capital A is 65, according
to the ASCII character set, and Java adopted this as part of its character support.

You must use an explicit cast to convert a value in a large type to a smaller type, or else
converting that value might result in a loss of precision. Explicit casts take the following form:

(typename)value

In the preceding example, typename is the name of the data type you're converting to, such as
short, int, or float. value is an expression that results in the value of the source type. For
example, the value of x is divided by the value of y, and the result is cast into an int in the
following expression:

(int)(x / y);

Note that because the precedence of casting is higher than that of arithmetic, you have to use
parentheses here; otherwise, the value of x would be cast into an int first and then divided by y,
which could easily produce a different result.

Casting Objects

Instances of classes also can be cast into instances of other classes, with one restriction: The
source and destination classes must be related by inheritance; one class must be a subclass of the
other.

Analogous to converting a primitive value to a larger type, some objects might not need to be
cast explicitly. In particular, because a subclass contains all the same information as its
superclass, you can use an instance of a subclass anywhere a superclass is expected.

For example, consider a method that takes two arguments, one of type Object and another of
type Window. You can pass an instance of any class for the Object argument because all Java
classes are subclasses of Object. For the Window argument, you can pass in its subclasses, such
as Dialog, FileDialog, and Frame.
This is true anywhere in a program, not just inside method calls. If you had a variable defined as
class Window, you could assign objects of that class or any of its subclasses to that variable
without casting.

This is true in the reverse, and you can use a superclass when a subclass is expected. There is a
catch, however: Because subclasses contain more behavior than their superclasses, there's a loss
in precision involved. Those superclass objects might not have all the behavior needed to act in
place of a subclass object. For example, if you have an operation that calls methods in objects of
the class Integer, using an object of class Number won't include many methods specified in
Integer. Errors occur if you try to call methods that the destination object doesn't have.

To use superclass objects where subclass objects are expected, you must cast them explicitly.
You won't lose any information in the cast, but you gain all the methods and variables that the
subclass defines. To cast an object to another class, you use the same operation as for primitive
types:

(classname)object

In this case, classname is the name of the destination class, and object is a reference to the
source object. Note that casting creates a reference to the old object of the type classname; the
old object continues to exist as it did before.

The following example casts an instance of the class VicePresident to an instance of the class
Employee; VicePresident is a subclass of Employee with more information, which here defines
that the VicePresident has executive washroom privileges:

Employee emp = new Employee();


VicePresident veep = new VicePresident();
emp = veep; // no cast needed for upward use
veep = (VicePresident)emp; // must cast explicitly

Casting one object is necessary whenever you use Java2D graphics operations. You must cast a
Graphics object to a Graphics2D object before you can draw onscreen. The following example
uses a Graphics object called screen to create a new Graphics2D object called screen2D:

Graphics2D screen2D = (Graphics2D)screen;

Graphics2D is a subclass of Graphics, and both are in the java.awt package. You explore the
subject fully during Day 13, "Color, Fonts, and Graphics."

In addition to casting objects to classes, you also can cast objects to interfaces, but only if an
object's class or one of its superclasses actually implements the interface. Casting an object to an
interface means that you can call one of that interface's methods even if that object's class does
not actually implement that interface.
Converting Primitive Types to Objects and Vice Versa

One thing you can't do under any circumstance is cast from an object to a primitive data type, or
vice versa.

Primitive types and objects are very different things in Java, and you can't automatically cast
between the two or use them interchangeably.

As an alternative, the java.lang package includes classes that correspond to each primitive data
type: Float, Boolean, Byte, and so on. Most of these classes have the same names as the data
types, except that the class names begin with a capital letter (Short instead of short, Double
instead of double, and the like). Also, two classes have names that differ from the corresponding
data type: Character is used for char variables and Integer for int variables.

Java treats the data types and their class versions very differently, and a program won't compile
successfully if you use one when the other is expected.

Using the classes that correspond to each primitive type, you can create an object that holds the
same value. The following statement creates an instance of the Integer class with the integer
value 7801:

Integer dataCount = new Integer(7801);

After you have an object created in this manner, you can use it as you would any object
(although you cannot change its value). When you want to use that value again as a primitive
value, there are methods for that, as well. For example, if you wanted to get an int value from a
dataCount object, the following statement would be apt:

int newCount = dataCount.intValue(); // returns 7801

A common translation you need in programs is converting a String to a numeric type, such as
an integer. When you need an int as the result, this can be done by using the parseInt() class
method of the Integer class. The String to convert is the only argument sent to the method, as
in the following example:

String pennsylvania = "65000";


int penn = Integer.parseInt(pennsylvania);

The following classes can be used to work with objects instead of primitive data types: Boolean,
Byte, Character, Double, Float, Integer, Long, Short, and Void.

CAUTION

The Void class represents nothing in Java, so there's no reason it would be used when translating
between primitive values and objects. It's a placeholder for the void keyword, which is used in
method definitions to indicate that the method does not return a value
Wrapper Classes
In this section you will learn about Wrapper classes and all the methods that manipulate data
and allows to operate a certain work.

Wrapper class is a wrapper around a primitive data type. It represents primitive data types in
their corresponding class instances e.g. a boolean data type can be represented as a Boolean class
instance. All of the primitive wrapper classes in Java are immutable i.e. once assigned a value to
a wrapper class instance cannot be changed further.

Wrapper Classes are used broadly with Collection classes in the java.util package and with the
classes in the java.lang.reflect reflection package.

Following table lists the primitive types and the corresponding wrapper classes:

Primitive Wrapper

boolean java.lang.Boolean

byte java.lang.Byte

char java.lang.Character

double java.lang.Double

float java.lang.Float

int java.lang.Integer

long java.lang.Long

short java.lang.Short

void java.lang.Void

In Java 5.0 version, additional wrapper classes were introduced in the


java.util.concurrent.atomic package. They provide atomic operations for assignment, addition
and increment. These classes act like variables and cannot be used as a substitute for the regular
wrapper classes. Few of these new wrapper classes like AtomicInteger and AtomicLong are the
subclasses of the Number Classes.
Primitive Wrapper

boolean AtomicBoolean

int AtomicInteger

long AtomicLong

V AtomicReference<V>

Features Of the Wrapper Classes

Some of the sound features maintained by the Wrapper Classes are as under :

 All the methods of the wrapper classes are static.


 The Wrapper class does not contain constructors.
 Once a value is assigned to a wrapper class instance it can not be changed, anymore.

Wrapper Classes : Methods with examples

There are some of the methods of the Wrapper class which are used to manipulate the data. Few
of them are given below:

1. add(int, Object): Learn to insert an element at the specified position.

2. add(Object): Learn to insert an object at the end of a list.

3. addAll(ArrayList): Learn to insert an array list of objects to another list.

4. get(): Learn to retrieve the elements contained with in an ArrayList object.

5. Integer.toBinaryString(): Learn to convert the Integer type object to a String object.

6. size(): Learn to get the dynamic capacity of a list.

7. remove(): Learn to remove an element from a particular position specified by a index value.

8. set(int, Object): Learn to replacace an element at the position specified by a index value.

The Numbers Classes


When working with numbers, most of the time you use the primitive types in your code. For
example:
int i = 500;
float gpa = 3.65f;
byte mask = 0xff;

There are, however, reasons to use objects in place of primitives, and the Java platform provides
wrapper classes for each of the primitive data types. These classes "wrap" the primitive in an
object. Often, the wrapping is done by the compiler—if you use a primitive where an object is
expected, the compiler boxes the primitive in its wrapper class for you. Similarly, if you use a
number object when a primitive is expected, the compiler unboxes the object for you.

Here is an example of boxing and unboxing:

Integer x, y;
x = 12;
y = 15;
System.out.println(x+y);

When x and y are assigned integer values, the compiler boxes the integers because x and y are
integer objects. In the println() statement, x and y are unboxed so that they can be added as
integers.

All of the numeric wrapper classes are subclasses of the abstract class Number:

Note: There are four other subclasses of Number that are not discussed here. BigDecimal and
BigInteger are used for high-precision calculations. AtomicInteger and AtomicLong are used
for multi-threaded applications.

There are three reasons that you might use a Number object rather than a primitive:

1. As an argument of a method that expects an object (often used when manipulating


collections of numbers).
2. To use constants defined by the class, such as MIN_VALUE and MAX_VALUE, that provide
the upper and lower bounds of the data type.
3. To use class methods for converting values to and from other primitive types, for
converting to and from strings, and for converting between number systems (decimal,
octal, hexadecimal, binary).
The following table lists the instance methods that all the subclasses of the Number class
implement.

Methods Implemented by all Subclasses of Number


Method Description
byte byteValue()
short shortValue()
int intValue() Converts the value of this Number object to the primitive data
long longValue() type returned.
float floatValue()
double doubleValue()

int compareTo(Byte
anotherByte)
int compareTo(Double
anotherDouble)
int compareTo(Float
anotherFloat)
int compareTo(Integer Compares this Number object to the argument.
anotherInteger)
int compareTo(Long
anotherLong)
int compareTo(Short
anotherShort)

Determines whether this number object is equal to the


argument.
boolean equals(Object The methods return true if the argument is not null and is an
obj) object of the same type and with the same numeric value.
There are some extra requirements for Double and Float
objects that are described in the Java API documentation.

Each Number class contains other methods that are useful for converting numbers to and from
strings and for converting between number systems. The following table lists these methods in
the Integer class. Methods for the other Number subclasses are similar:

Conversion Methods, Integer Class


Method Description
static Integer Decodes a string into an integer. Can accept string representations
decode(String s) of decimal, octal, or hexadecimal numbers as input.
static int
parseInt(String s) Returns an integer (decimal only).

static int Returns an integer, given a string representation of decimal, binary,


parseInt(String s, octal, or hexadecimal (radix equals 10, 2, 8, or 16 respectively)
int radix) numbers as input.
String toString() Returns a String object representing the value of this Integer.
static String
toString(int i) Returns a String object representing the specified integer.

static Integer Returns an Integer object holding the value of the specified
valueOf(int i) primitive.
static Integer Returns an Integer object holding the value of the specified string
valueOf(String s) representation.

Returns an Integer object holding the integer value of the


static Integer
valueOf(String s, int
specified string representation, parsed with the value of radix. For
radix) example, if s = "333" and radix = 8, the method returns the base-ten
integer equivalent of the octal number 333.

Formatting Numeric Print Output


Earlier you saw the use of the print and println methods for printing strings to standard output
(System.out). Since all numbers can be converted to strings (as you will see later in this lesson),
you can use these methods to print out an arbitrary mixture of strings and numbers. The Java
programming language has other methods, however, that allow you to exercise much more
control over your print output when numbers are included.

The printf and format Methods

The java.io package includes a PrintStream class that has two formatting methods that you
can use to replace print and println. These methods, format and printf, are equivalent to
one another. The familiar System.out that you have been using happens to be a PrintStream
object, so you can invoke PrintStream methods on System.out. Thus, you can use format or
printf anywhere in your code where you have previously been using print or println. For
example,

System.out.format(.....);

The syntax for these two java.io.PrintStream methods is the same:

public PrintStream format(String format, Object... args)

where format is a string that specifies the formatting to be used and args is a list of the
variables to be printed using that formatting. A simple example would be

System.out.format("The value of " + "the float variable is " +


"%f, while the value of the " + "integer variable is %d, " +
"and the string is %s", floatVar, intVar, stringVar);
The first parameter, format, is a format string specifying how the objects in the second
parameter, args, are to be formatted. The format string contains plain text as well as format
specifiers, which are special characters that format the arguments of Object... args. (The
notation Object... args is called varargs, which means that the number of arguments may
vary.)

Format specifiers begin with a percent sign (%) and end with a converter. The converter is a
character indicating the type of argument to be formatted. In between the percent sign (%) and
the converter you can have optional flags and specifiers. There are many converters, flags, and
specifiers, which are documented in java.util.Formatter

Here is a basic example:

int i = 461012;
System.out.format("The value of i is: %d%n", i);

The %d specifies that the single variable is a decimal integer. The %n is a platform-independent
newline character. The output is:

The value of i is: 461012

The printf and format methods are overloaded. Each has a version with the following syntax:

public PrintStream format(Locale l, String format, Object... args)

To print numbers in the French system (where a comma is used in place of the decimal place in
the English representation of floating point numbers), for example, you would use:

System.out.format(Locale.FRANCE,
"The value of the float " + "variable is %f, while the " +
"value of the integer variable " + "is %d, and the string is %s%n",
floatVar, intVar, stringVar);

An Example

The following table lists some of the converters and flags that are used in the sample program,
TestFormat.java, that follows the table.

Converters and Flags Used in TestFormat.java

Converter Flag Explanation

d A decimal integer.
f A float.

A new line character appropriate to the platform


n running the application. You should always use
%n, rather than \n.

A date & time conversion—locale-specific full


tB
name of month.

A date & time conversion—2-digit day of month.


td, te
td has leading zeroes as needed, te does not.

A date & time conversion—ty = 2-digit year, tY =


ty, tY
4-digit year.

tl A date & time conversion—hour in 12-hour clock.

A date & time conversion—minutes in 2 digits,


tM
with leading zeroes as necessary.

A date & time conversion—locale-specific am/pm


tp
(lower case).

A date & time conversion—months in 2 digits,


tm
with leading zeroes as necessary.

tD A date & time conversion—date as %tm%td%ty

Eight characters in width, with leading zeroes as


08
necessary.

+ Includes sign, whether positive or negative.

, Includes locale-specific grouping characters.

- Left-justified..
.3 Three places after decimal point.

Ten characters in width, right justified, with three


10.3
places after decimal point.

The following program shows some of the formatting that you can do with format. The output is
shown within double quotes in the embedded comment:

import java.util.Calendar;
import java.util.Locale;

public class TestFormat {

public static void main(String[] args) {


long n = 461012;
System.out.format("%d%n", n); // --> "461012"
System.out.format("%08d%n", n); // --> "00461012"
System.out.format("%+8d%n", n); // --> " +461012"
System.out.format("%,8d%n", n); // --> " 461,012"
System.out.format("%+,8d%n%n", n); // --> "+461,012"

double pi = Math.PI;

System.out.format("%f%n", pi); // --> "3.141593"


System.out.format("%.3f%n", pi); // --> "3.142"
System.out.format("%10.3f%n", pi); // --> " 3.142"
System.out.format("%-10.3f%n", pi); // --> "3.142"
System.out.format(Locale.FRANCE,
"%-10.4f%n%n", pi); // --> "3,1416"

Calendar c = Calendar.getInstance();
System.out.format("%tB %te, %tY%n", c, c, c); // --> "May 29, 2006"

System.out.format("%tl:%tM %tp%n", c, c, c); // --> "2:34 am"

System.out.format("%tD%n", c); // --> "05/29/06"


}
}

Note:

The discussion in this section covers just the basics of the format and printf methods. Further
detail can be found in the Basic I/O section of the Essential trail, in the "Formatting" page.

Using String.format to create strings is covered in Strings.


The DecimalFormat Class

You can use the java.text.DecimalFormat class to control the display of leading and trailing
zeros, prefixes and suffixes, grouping (thousands) separators, and the decimal separator.
DecimalFormat offers a great deal of flexibility in the formatting of numbers, but it can make
your code more complex.

The example that follows creates a DecimalFormat object, myFormatter, by passing a pattern
string to the DecimalFormat constructor. The format() method, which DecimalFormat inherits
from NumberFormat, is then invoked by myFormatter—it accepts a double value as an
argument and returns the formatted number in a string:

Here is a sample program that illustrates the use of DecimalFormat:

import java.text.*;

public class DecimalFormatDemo {

static public void customFormat(String pattern, double value ) {


DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(value + " " + pattern + " " + output);
}

static public void main(String[] args) {

customFormat("###,###.###", 123456.789);
customFormat("###.##", 123456.789);
customFormat("000000.000", 123.78);
customFormat("$###,###.###", 12345.67);
}
}

The output is:

123456.789 ###,###.### 123,456.789


123456.789 ###.## 123456.79
123.78 000000.000 000123.780
12345.67 $###,###.### $12,345.67

The following table explains each line of output.

DecimalFormat.java Output

Value Pattern Output Explanation


The pound sign (#) denotes a digit, the comma is a
123456.789 ###,###.### 123,456.789 placeholder for the grouping separator, and the period is a
placeholder for the decimal separator.

The value has three digits to the right of the decimal


123456.789 ###.## 123456.79 point, but the pattern has only two. The format method
handles this by rounding up.

The pattern specifies leading and trailing zeros, because


123.78 000000.000 000123.780
the 0 character is used instead of the pound sign (#).

The first character in the pattern is the dollar sign ($).


12345.67 $###,###.### $12,345.67 Note that it immediately precedes the leftmost digit in the
formatted output.

You use one of the wrapper classes – Byte, Double, Float, Integer, Long, or Short – to wrap a
number of primitive type in an object. The Java compiler automatically wraps (boxes) primitives
for you when necessary and unboxes them, again when necessary.

The Number classes include constants and useful class methods. The MIN_VALUE and MAX_VALUE
constants contain the smallest and largest values that can be contained by an object of that type.
The byteValue, shortValue, and similar methods convert one numeric type to another. The
valueOf method converts a string to a number, and the toString method converts a number to a
string.

To format a string containing numbers for output, you can use the printf() or format()
methods in the PrintStream class. Alternatively, you can use the NumberFormat class to
customize numerical formats using patterns.

The Math class contains a variety of class methods for performing mathematical functions,
including exponential, logarithmic, and trigonometric methods. Math also includes basic
arithmetic functions, such as absolute value and rounding, and a method, random(), for
generating random number.

java.text
Class DateFormat
java.lang.Object
java.text.Format
java.text.DateFormat
All Implemented Interfaces:
Serializable, Cloneable

Direct Known Subclasses:

SimpleDateFormat

public abstract class DateFormat


extends Format

DateFormat is an abstract class for date/time formatting subclasses which formats and parses
dates or time in a language-independent manner. The date/time formatting subclass, such as
SimpleDateFormat, allows for formatting (i.e., date -> text), parsing (text -> date), and
normalization. The date is represented as a Date object or as the milliseconds since January 1,
1970, 00:00:00 GMT.

DateFormat provides many class methods for obtaining default date/time formatters based on the
default or a given locale and a number of formatting styles. The formatting styles include FULL,
LONG, MEDIUM, and SHORT. More detail and examples of using these styles are provided in
the method descriptions.

DateFormat helps you to format and parse dates for any locale. Your code can be completely
independent of the locale conventions for months, days of the week, or even the calendar format:
lunar vs. solar.

To format a date for the current Locale, use one of the static factory methods:

myString = DateFormat.getDateInstance().format(myDate);

If you are formatting multiple dates, it is more efficient to get the format and use it multiple
times so that the system doesn't have to fetch the information about the local language and
country conventions multiple times.

DateFormat df = DateFormat.getDateInstance();
for (int i = 0; i < myDate.length; ++i) {
output.println(df.format(myDate[i]) + "; ");
}

To format a date for a different Locale, specify it in the call to getDateInstance().

DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE);

You can use a DateFormat to parse also.


myDate = df.parse(myString);

Use getDateInstance to get the normal date format for that country. There are other static factory
methods available. Use getTimeInstance to get the time format for that country. Use
getDateTimeInstance to get a date and time format. You can pass in different options to these
factory methods to control the length of the result; from SHORT to MEDIUM to LONG to
FULL. The exact result depends on the locale, but generally:

 SHORT is completely numeric, such as 12.13.52 or 3:30pm


 MEDIUM is longer, such as Jan 12, 1952
 LONG is longer, such as January 12, 1952 or 3:30:32pm
 FULL is pretty completely specified, such as Tuesday, April 12, 1952 AD or 3:30:42pm PST.

You can also set the time zone on the format if you wish. If you want even more control over the
format or parsing, (or want to give your users more control), you can try casting the DateFormat
you get from the factory methods to a SimpleDateFormat. This will work for the majority of
countries; just remember to put it in a try block in case you encounter an unusual one.

You can also use forms of the parse and format methods with ParsePosition and FieldPosition to
allow you to

 progressively parse through pieces of a string.


 align any particular field, or find out where it is for selection on the screen.

Synchronization

Date formats are not synchronized. It is recommended to create separate format instances for
each thread. If multiple threads access a format concurrently, it must be synchronized externally.

See Also:

Format, NumberFormat, SimpleDateFormat, Calendar, GregorianCalendar, TimeZone,


Serialized Form

Nested Class Summary


static class DateFormat.Field
Defines constants that are used as attribute keys in the
AttributedCharacterIterator returned from
DateFormat.formatToCharacterIterator and as field identifiers in
FieldPosition.
Field Summary
static int AM_PM_FIELD
Useful constant for AM_PM field alignment.

protected Calendar calendar


The calendar that DateFormat uses to produce the time field
values needed to implement date and time formatting.

static int DATE_FIELD


Useful constant for DATE field alignment.

static int DAY_OF_WEEK_FIELD


Useful constant for DAY_OF_WEEK field alignment.

static int DAY_OF_WEEK_IN_MONTH_FIELD


Useful constant for DAY_OF_WEEK_IN_MONTH field alignment.

static int DAY_OF_YEAR_FIELD


Useful constant for DAY_OF_YEAR field alignment.

static int DEFAULT


Constant for default style pattern.

static int ERA_FIELD


Useful constant for ERA field alignment.

static int FULL


Constant for full style pattern.

static int HOUR_OF_DAY0_FIELD


Useful constant for zero-based HOUR_OF_DAY field alignment.

static int HOUR_OF_DAY1_FIELD


Useful constant for one-based HOUR_OF_DAY field alignment.

static int HOUR0_FIELD


Useful constant for zero-based HOUR field alignment.

static int HOUR1_FIELD


Useful constant for one-based HOUR field alignment.

static int LONG


Constant for long style pattern.

static int MEDIUM


Constant for medium style pattern.

static int MILLISECOND_FIELD


Useful constant for MILLISECOND field alignment.

static int MINUTE_FIELD


Useful constant for MINUTE field alignment.

static int MONTH_FIELD


Useful constant for MONTH field alignment.

protected NumberFormat numberFormat


The number formatter that DateFormat uses to format numbers
in dates and times.

static int SECOND_FIELD


Useful constant for SECOND field alignment.

static int SHORT


Constant for short style pattern.

static int TIMEZONE_FIELD


Useful constant for TIMEZONE field alignment.

static int WEEK_OF_MONTH_FIELD


Useful constant for WEEK_OF_MONTH field alignment.

static int WEEK_OF_YEAR_FIELD


Useful constant for WEEK_OF_YEAR field alignment.

static int YEAR_FIELD


Useful constant for YEAR field alignment.
Constructor Summary
protected DateFormat()
Create a new date format.

Method Summary
Object clone()
Overrides Cloneable

boolean equals(Object obj)


Overrides equals

String format(Date date)


Formats a Date into a date/time string.

abstract StringBuffer format(Date date, StringBuffer toAppendTo,


FieldPosition fieldPosition)
Formats a Date into a date/time string.

StringBuffer format(Object obj, StringBuffer toAppendTo,


FieldPosition fieldPosition)
Overrides Format.

static Locale[] getAvailableLocales()


Returns an array of all locales for which the get*Instance
methods of this class can return localized instances.

Calendar getCalendar()
Gets the calendar associated with this date/time formatter.

static DateFormat getDateInstance()


Gets the date formatter with the default formatting style for the
default locale.

static DateFormat getDateInstance(int style)


Gets the date formatter with the given formatting style for the
default locale.
static DateFormat getDateInstance(int style, Locale aLocale)
Gets the date formatter with the given formatting style for the
given locale.

static DateFormat getDateTimeInstance()


Gets the date/time formatter with the default formatting style for
the default locale.

static DateFormat getDateTimeInstance(int dateStyle, int timeStyle)


Gets the date/time formatter with the given date and time
formatting styles for the default locale.

static DateFormat getDateTimeInstance(int dateStyle, int timeStyle,


Locale aLocale)
Gets the date/time formatter with the given formatting styles for
the given locale.

static DateFormat getInstance()


Get a default date/time formatter that uses the SHORT style for
both the date and the time.

NumberFormat getNumberFormat()
Gets the number formatter which this date/time formatter uses to
format and parse a time.

static DateFormat getTimeInstance()


Gets the time formatter with the default formatting style for the
default locale.

static DateFormat getTimeInstance(int style)


Gets the time formatter with the given formatting style for the
default locale.

static DateFormat getTimeInstance(int style, Locale aLocale)


Gets the time formatter with the given formatting style for the
given locale.

TimeZone getTimeZone()
Gets the time zone.

int hashCode()
Overrides hashCode
boolean isLenient()
Tell whether date/time parsing is to be lenient.

Date parse(String source)


Parses text from the beginning of the given string to produce a
date.

abstract Date parse(String source, ParsePosition pos)


Parse a date/time string according to the given parse position.

Object parseObject(String source, ParsePosition pos)


Parses text from a string to produce a Date.

void setCalendar(Calendar newCalendar)


Set the calendar to be used by this date format.

void setLenient(boolean lenient)


Specify whether or not date/time parsing is to be lenient.

void setNumberFormat(NumberFormat newNumberFormat)


Allows you to set the number formatter.

void setTimeZone(TimeZone zone)


Sets the time zone for the calendar of this DateFormat object.

Methods inherited from class java.text.Format

format, formatToCharacterIterator, parseObject

Methods inherited from class java.lang.Object

finalize, getClass, notify, notifyAll, toString, wait, wait, wait

Field Detail
calendar
protected Calendar calendar
The calendar that DateFormat uses to produce the time field values needed to implement date
and time formatting. Subclasses should initialize this to a calendar appropriate for the locale
associated with this DateFormat.

numberFormat
protected NumberFormat numberFormat
The number formatter that DateFormat uses to format numbers in dates and times. Subclasses
should initialize this to a number format appropriate for the locale associated with this
DateFormat.

ERA_FIELD
public static final int ERA_FIELD
Useful constant for ERA field alignment. Used in FieldPosition of date/time formatting.

See Also:

Constant Field Values

YEAR_FIELD
public static final int YEAR_FIELD
Useful constant for YEAR field alignment. Used in FieldPosition of date/time formatting.

See Also:

Constant Field Values

MONTH_FIELD
public static final int MONTH_FIELD
Useful constant for MONTH field alignment. Used in FieldPosition of date/time formatting.

See Also:

Constant Field Values

DATE_FIELD
public static final int DATE_FIELD
Useful constant for DATE field alignment. Used in FieldPosition of date/time formatting.
See Also:

Constant Field Values

HOUR_OF_DAY1_FIELD
public static final int HOUR_OF_DAY1_FIELD
Useful constant for one-based HOUR_OF_DAY field alignment. Used in FieldPosition of
date/time formatting. HOUR_OF_DAY1_FIELD is used for the one-based 24-hour clock. For
example, 23:59 + 01:00 results in 24:59.

See Also:

Constant Field Values

HOUR_OF_DAY0_FIELD
public static final int HOUR_OF_DAY0_FIELD
Useful constant for zero-based HOUR_OF_DAY field alignment. Used in FieldPosition of
date/time formatting. HOUR_OF_DAY0_FIELD is used for the zero-based 24-hour clock. For
example, 23:59 + 01:00 results in 00:59.

See Also:

Constant Field Values

MINUTE_FIELD
public static final int MINUTE_FIELD
Useful constant for MINUTE field alignment. Used in FieldPosition of date/time formatting.

See Also:

Constant Field Values

SECOND_FIELD
public static final int SECOND_FIELD
Useful constant for SECOND field alignment. Used in FieldPosition of date/time formatting.

See Also:

Constant Field Values


MILLISECOND_FIELD
public static final int MILLISECOND_FIELD
Useful constant for MILLISECOND field alignment. Used in FieldPosition of date/time formatting.

See Also:

Constant Field Values

DAY_OF_WEEK_FIELD
public static final int DAY_OF_WEEK_FIELD
Useful constant for DAY_OF_WEEK field alignment. Used in FieldPosition of date/time
formatting.

See Also:

Constant Field Values

DAY_OF_YEAR_FIELD
public static final int DAY_OF_YEAR_FIELD
Useful constant for DAY_OF_YEAR field alignment. Used in FieldPosition of date/time
formatting.

See Also:

Constant Field Values

DAY_OF_WEEK_IN_MONTH_FIELD
public static final int DAY_OF_WEEK_IN_MONTH_FIELD
Useful constant for DAY_OF_WEEK_IN_MONTH field alignment. Used in FieldPosition of
date/time formatting.

See Also:

Constant Field Values

WEEK_OF_YEAR_FIELD
public static final int WEEK_OF_YEAR_FIELD
Useful constant for WEEK_OF_YEAR field alignment. Used in FieldPosition of date/time
formatting.

See Also:
Constant Field Values

WEEK_OF_MONTH_FIELD
public static final int WEEK_OF_MONTH_FIELD
Useful constant for WEEK_OF_MONTH field alignment. Used in FieldPosition of date/time
formatting.

See Also:

Constant Field Values

AM_PM_FIELD
public static final int AM_PM_FIELD
Useful constant for AM_PM field alignment. Used in FieldPosition of date/time formatting.

See Also:

Constant Field Values

HOUR1_FIELD
public static final int HOUR1_FIELD
Useful constant for one-based HOUR field alignment. Used in FieldPosition of date/time
formatting. HOUR1_FIELD is used for the one-based 12-hour clock. For example, 11:30 PM + 1
hour results in 12:30 AM.

See Also:

Constant Field Values

HOUR0_FIELD
public static final int HOUR0_FIELD
Useful constant for zero-based HOUR field alignment. Used in FieldPosition of date/time
formatting. HOUR0_FIELD is used for the zero-based 12-hour clock. For example, 11:30 PM + 1
hour results in 00:30 AM.

See Also:

Constant Field Values


TIMEZONE_FIELD
public static final int TIMEZONE_FIELD
Useful constant for TIMEZONE field alignment. Used in FieldPosition of date/time formatting.

See Also:

Constant Field Values

FULL
public static final int FULL
Constant for full style pattern.

See Also:

Constant Field Values

LONG
public static final int LONG
Constant for long style pattern.

See Also:

Constant Field Values

MEDIUM
public static final int MEDIUM
Constant for medium style pattern.

See Also:

Constant Field Values

SHORT
public static final int SHORT
Constant for short style pattern.

See Also:

Constant Field Values


DEFAULT
public static final int DEFAULT
Constant for default style pattern. Its value is MEDIUM.

See Also:

Constant Field Values

Constructor Detail

DateFormat
protected DateFormat()
Create a new date format.

Method Detail

format
public final StringBuffer format(Object obj,
StringBuffer toAppendTo,
FieldPosition fieldPosition)
Overrides Format. Formats a time object into a time string. Examples of time objects are a time
value expressed in milliseconds and a Date object.

Specified by:

format in class Format

Parameters:

obj - must be a Number or a Date.

toAppendTo - the string buffer for the returning time string.

fieldPosition - keeps track of the position of the field within the returned string. On input:
an alignment field, if desired. On output: the offsets of the alignment field. For example, given a
time text "1996.07.10 AD at 15:08:56 PDT", if the given fieldPosition is DateFormat.YEAR_FIELD,
the begin index and end index of fieldPosition will be set to 0 and 4, respectively. Notice that if
the same time field appears more than once in a pattern, the fieldPosition will be set for the first
occurrence of that time field. For instance, formatting a Date to the time string "1 PM PDT
(Pacific Daylight Time)" using the pattern "h a z (zzzz)" and the alignment field
DateFormat.TIMEZONE_FIELD, the begin index and end index of fieldPosition will be set to 5 and
8, respectively, for the first occurrence of the timezone pattern character 'z'.

Returns:
the string buffer passed in as toAppendTo, with formatted text appended.

See Also:

Format

format
public abstract StringBuffer format(Date date,
StringBuffer toAppendTo,
FieldPosition fieldPosition)
Formats a Date into a date/time string.

Parameters:

date - a Date to be formatted into a date/time string.

toAppendTo - the string buffer for the returning date/time string.

fieldPosition - keeps track of the position of the field within the returned string. On input:
an alignment field, if desired. On output: the offsets of the alignment field. For example, given a
time text "1996.07.10 AD at 15:08:56 PDT", if the given fieldPosition is DateFormat.YEAR_FIELD,
the begin index and end index of fieldPosition will be set to 0 and 4, respectively. Notice that if
the same time field appears more than once in a pattern, the fieldPosition will be set for the first
occurrence of that time field. For instance, formatting a Date to the time string "1 PM PDT
(Pacific Daylight Time)" using the pattern "h a z (zzzz)" and the alignment field
DateFormat.TIMEZONE_FIELD, the begin index and end index of fieldPosition will be set to 5 and
8, respectively, for the first occurrence of the timezone pattern character 'z'.

Returns:

the string buffer passed in as toAppendTo, with formatted text appended.

format
public final String format(Date date)
Formats a Date into a date/time string.

Parameters:

date - the time value to be formatted into a time string.

Returns:

the formatted time string.


parse
public Date parse(String source)
throws ParseException
Parses text from the beginning of the given string to produce a date. The method may not use
the entire text of the given string.

See the parse(String, ParsePosition) method for more information on date parsing.

Parameters:

source - A String whose beginning should be parsed.

Returns:

A Date parsed from the string.

Throws:

ParseException - if the beginning of the specified string cannot be parsed.

parse
public abstract Date parse(String source,
ParsePosition pos)
Parse a date/time string according to the given parse position. For example, a time text
"07/10/96 4:5 PM, PDT" will be parsed into a Date that is equivalent to Date(837039928046).

By default, parsing is lenient: If the input is not in the form used by this object's format
method but can still be parsed as a date, then the parse succeeds. Clients may insist on
strict adherence to the format by calling setLenient(false).

Parameters:

source - The date/time string to be parsed

pos - On input, the position at which to start parsing; on output, the position at which parsing
terminated, or the start position if the parse failed.

Returns:

A Date, or null if the input could not be parsed

See Also:

setLenient(boolean)
parseObject
public Object parseObject(String source,
ParsePosition pos)
Parses text from a string to produce a Date.

The method attempts to parse text starting at the index given by pos. If parsing succeeds,
then the index of pos is updated to the index after the last character used (parsing does
not necessarily use all characters up to the end of the string), and the parsed date is
returned. The updated pos can be used to indicate the starting point for the next call to
this method. If an error occurs, then the index of pos is not changed, the error index of
pos is set to the index of the character where the error occurred, and null is returned.

See the parse(String, ParsePosition) method for more information on date parsing.

Specified by:

parseObject in class Format

Parameters:

source - A String, part of which should be parsed.

pos - A ParsePosition object with index and error index information as described above.

Returns:

A Date parsed from the string. In case of error, returns null.

Throws:

NullPointerException - if pos is null.

getTimeInstance
public static final DateFormat getTimeInstance()
Gets the time formatter with the default formatting style for the default locale.

Returns:

a time formatter.

getTimeInstance
public static final DateFormat getTimeInstance(int style)
Gets the time formatter with the given formatting style for the default locale.

Parameters:
style - the given formatting style. For example, SHORT for "h:mm a" in the US locale.

Returns:

a time formatter.

getTimeInstance
public static final DateFormat getTimeInstance(int style,
Locale aLocale)
Gets the time formatter with the given formatting style for the given locale.

Parameters:

style - the given formatting style. For example, SHORT for "h:mm a" in the US locale.

aLocale - the given locale.

Returns:

a time formatter.

getDateInstance
public static final DateFormat getDateInstance()
Gets the date formatter with the default formatting style for the default locale.

Returns:

a date formatter.

getDateInstance
public static final DateFormat getDateInstance(int style)
Gets the date formatter with the given formatting style for the default locale.

Parameters:

style - the given formatting style. For example, SHORT for "M/d/yy" in the US locale.

Returns:

a date formatter.
getDateInstance
public static final DateFormat getDateInstance(int style,
Locale aLocale)
Gets the date formatter with the given formatting style for the given locale.

Parameters:

style - the given formatting style. For example, SHORT for "M/d/yy" in the US locale.

aLocale - the given locale.

Returns:

a date formatter.

getDateTimeInstance
public static final DateFormat getDateTimeInstance()
Gets the date/time formatter with the default formatting style for the default locale.

Returns:

a date/time formatter.

getDateTimeInstance
public static final DateFormat getDateTimeInstance(int dateStyle,
int timeStyle)
Gets the date/time formatter with the given date and time formatting styles for the default
locale.

Parameters:

dateStyle - the given date formatting style. For example, SHORT for "M/d/yy" in the US locale.

timeStyle - the given time formatting style. For example, SHORT for "h:mm a" in the US locale.

Returns:

a date/time formatter.

getDateTimeInstance
public static final DateFormat getDateTimeInstance(int dateStyle,
int timeStyle,
Locale aLocale)
Gets the date/time formatter with the given formatting styles for the given locale.
Parameters:

dateStyle - the given date formatting style.

timeStyle - the given time formatting style.

aLocale - the given locale.

Returns:

a date/time formatter.

getInstance
public static final DateFormat getInstance()
Get a default date/time formatter that uses the SHORT style for both the date and the time.

getAvailableLocales
public static Locale[] getAvailableLocales()
Returns an array of all locales for which the get*Instance methods of this class can return
localized instances. The returned array represents the union of locales supported by the Java
runtime and by installed DateFormatProvider implementations. It must contain at least a
Locale instance equal to Locale.US.

Returns:

An array of locales for which localized DateFormat instances are available.

setCalendar
public void setCalendar(Calendar newCalendar)
Set the calendar to be used by this date format. Initially, the default calendar for the specified or
default locale is used.

Parameters:

newCalendar - the new Calendar to be used by the date format

getCalendar
public Calendar getCalendar()
Gets the calendar associated with this date/time formatter.

Returns:
the calendar associated with this date/time formatter.

setNumberFormat
public void setNumberFormat(NumberFormat newNumberFormat)
Allows you to set the number formatter.

Parameters:

newNumberFormat - the given new NumberFormat.

getNumberFormat
public NumberFormat getNumberFormat()
Gets the number formatter which this date/time formatter uses to format and parse a time.

Returns:

the number formatter which this date/time formatter uses.

setTimeZone
public void setTimeZone(TimeZone zone)
Sets the time zone for the calendar of this DateFormat object.

Parameters:

zone - the given new time zone.

getTimeZone
public TimeZone getTimeZone()
Gets the time zone.

Returns:

the time zone associated with the calendar of DateFormat.

hashCode
public int hashCode()
Overrides hashCode
Overrides:

hashCode in class Object

Returns:

a hash code value for this object.

See Also:

Object.equals(java.lang.Object), Hashtable

equals
public boolean equals(Object obj)
Overrides equals

Overrides:

equals in class Object

Parameters:

obj - the reference object with which to compare.

Returns:

true if this object is the same as the obj argument; false otherwise.

Packages in Java
Introduction:
Given that packages exist and are a good mechanism for compartmentalizing diverse classes
from each other, it is easy to see why all of the built-in Java classes are stored in packages. There
are no core Java classes in the unnamed default package; all of the standard classes are stored in
some named package. Since classes within packages must be fully qualified with their package
name or names, it could become tedious to type in the long dot-separated package path name for
every class you want to use. For this reason, Java includes the import statement to bring certain
classes, or entire packages, into visibility. Once imported, a class can be referred to directly,
using only its name. The import statement is a convenience to the programmer and is not
technically needed to
write a complete Java program. If you are going to refer to a few dozen classes in your
application, however, the import statement will save a lot of typing.

In a Java source file, import statements occur immediately following the package statement (if
it exists) and before any class definitions. This is the general form of the import statement:
import pkg1[.pkg2].(classname|*);

Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate package
inside the outer package separated by a dot (.). There is no practical limit on the depth of a
package hierarchy, except that imposed by the file system. Finally, you specify either an explicit
classname or a star (*), which indicates that the Java compiler should import the entire package.
This code fragment shows both forms in use:

import java.util.Date;
import java.io.*;

Caution: The star form may increase compilation time—especially if you import several large
packages. For this reason it is a good idea to explicitly name the classes that you want to use
rather than importing whole packages. However, the star form has absolutely no effect on the
run-time performance or size of your classes.

All of the standard Java classes included with Java are stored in a package called java. The basic
language functions are stored in a package inside of the java package called java.lang.
Normally, you have to import every package or class that you want to use, but since Java is
useless without much of the functionality in java.lang, it is implicitly imported by the compiler
for all programs. This is equivalent to the following line being at the top of all of your programs:

import java.lang.*;

If a class with the same name exists in two different packages that you import using the star
form, the compiler will remain silent, unless you try to use one of the classes. In that case, you
will get a compile-time error and have to explicitly name the class specifying its package. Any
place you use a class name, you can use its fully qualified name, which includes its full package
hierarchy. For example, this fragment uses an import statement:

import java.util.*;
class MyDate extends Date {
}

The same example without the import statement looks like this:

class MyDate extends java.util.Date {


}

When a package is imported, only those items within the package declared as public will be
available to non-subclasses in the importing code. For example, if you want the Balance class of
the package MyPack shown earlier to be available as a stand-alone class for general use outside
of MyPack, then you will need to declare it as public and put it into its own file, as shown here:

package MyPack;
/* Now, the Balance class, its constructor, and its
show() method are public. This means that they can
be used by non-subclass code outside their package.
*/
public class Balance {
String name;
double bal;
public Balance(String n, double b) {
name = n;
bal = b;
}
public void show() {
if(bal<0)
System.out.print("—> ");
System.out.println(name + ": $" + bal);
}
}

As you can see, the Balance class is now public. Also, its constructor and its show( ) method are
public, too. This means that they can be accessed by any type of code outside the MyPack
package. For example, here TestBalance imports MyPack and is then able to make use of the
Balance class:

import MyPack.*;
class TestBalance {
public static void main(String args[]) {
/* Because Balance is public, you may use Balance
class and call its constructor. */
Balance test = new Balance("J. J. Jaspers", 99.88);
test.show(); // you may also call show()
}
}

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. You can put your types in packages too.

Suppose you write a group of classes that represent graphic objects, such as circles, rectangles,
lines, and points. You also write an interface, Draggable, that classes implement if they can be
dragged with the mouse.

//in the Draggable.java file


public interface Draggable {
...
}

//in the Graphic.java file


public abstract class Graphic {
...
}

//in the Circle.java file


public class Circle extends Graphic
implements Draggable {
. . .
}

//in the Rectangle.java file


public class Rectangle extends Graphic
implements Draggable {
. . .
}

//in the Point.java file


public class Point extends Graphic
implements Draggable {
. . .
}

//in the Line.java file


public class Line extends Graphic
implements Draggable {
. . .
}

You should bundle these classes and the interface in a package for several reasons, including the
following:

 You and other programmers can easily determine that these types are related.
 You and other programmers know where to find types that can provide graphics-related
functions.
 The names of your types won't conflict with the type names in other packages because
the package creates a new namespace.
 You can allow types within the package to have unrestricted access to one another yet
still restrict access for types outside the package.
Many times when we get a chance to work on a small project, one thing we intend to do is to put
all java files into one single directory. It is quick, easy and harmless. However if our small
project gets bigger, and the number of files is increasing, putting all these files into the same
directory would be a nightmare for us. In java we can avoid this sort of problem by using
Packages.

Packages are nothing more than the way we organize files into different directories according to
their functionality, usability as well as category they should belong to. An obvious example of
packaging is the JDK package from SUN (java.xxx.yyy) as shown below:

Figure 1. Basic structure of JDK package

Basically, files in one directory (or package) would have different functionality from those of
another directory. For example, files in java.io package do something related to I/O, but files in
java.net package give us the way to deal with the Network. In GUI applications, it's quite
common for us to see a directory with a name "ui" (user interface), meaning that this directory
keeps files related to the presentation part of the application. On the other hand, we would see a
directory called "engine", which stores all files related to the core functionality of the application
instead.

Packaging also help us to avoid class name collision when we use the same class name as that of
others. For example, if we have a class name called "Vector", its name would crash with the
Vector class from JDK. However, this never happens because JDK use java.util as a package
name for the Vector class (java.util.Vector). So our Vector class can be named as "Vector"
or we can put it into another package like com.mycompany.Vector without fighting with anyone.
The benefits of using package reflect the ease of maintenance, organization, and increase
collaboration among developers. Understanding the concept of package will also help us manage
and use files stored in jar files in more efficient ways.

How to create a package

Suppose we have a file called HelloWorld.java, and we want to put this file in a package
world. First thing we have to do is to specify the keyword package with the name of the
package we want to use (world in our case) on top of our source file, before the code that defines
the real classes in the package, as shown in our HelloWorld class below:

// only comment can be here


package world;

public class HelloWorld {


public static void main(String[] args) {
System.out.println("Hello World");
}
}

Setting up the CLASSPATH

From figure 2 we put the package world under C:. So we just set our CLASSPATH as:

set CLASSPATH=.;C:\;
We set the CLASSPATH to point to 2 places, . (dot) and C:\ directory.
Note: If you used to play around with DOS or UNIX, you may be familiar with . (dot) and .. (dot dot). We
use . as an alias for the current directory and .. for the parent directory. In our CLASSPATH we include
this . for convenient reason. Java will find our class file not only from C: directory but from the current
directory as well. Also, we use ; (semicolon) to separate the directory location in case we keep class files
in many places.

When compiling HelloWorld class, we just go to the world directory and type the command:

C:\world\javac HelloWorld.java
If you try to run this HelloWorld using java HelloWorld, you will get the following error:

C:\world>java HelloWorld
Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld (wrong
name:
world/HelloWorld)
at java.lang.ClassLoader.defineClass0(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:442)
at
java.security.SecureClassLoader.defineClass(SecureClassLoader.java:101)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:248)
at java.net.URLClassLoader.access$1(URLClassLoader.java:216)
at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:191)
at java.lang.ClassLoader.loadClass(ClassLoader.java:290)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:286)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
The reason is right now the HelloWorld class belongs to the package world. If we want to run it, we
have to tell JVM about its fully-qualified class name (world.HelloWorld) instead of its plain class
name (HelloWorld).

C:\world>java world.HelloWorld
C:\world>Hello World
Note: fully-qualified class name is the name of the java class that includes its package name

To make this example more understandable, let's put the HelloWorld class along with its
package (world) be under C:\myclasses directory instead. The new location of our HelloWorld
should be as shown in Figure 3:

Figure 3. HelloWorld class (in world package) under myclasses directory

We just changed the location of the package from C:\world\HelloWorld.java to


C:\myclasses\world\HelloWorld.java. Our CLASSPATH then needs to be changed to point to the
new location of the package world accordingly.

set CLASSPATH=.;C:\myclasses;
Thus, Java will look for java classes from the current directory and C:\myclasses directory instead.

Someone may ask "Do we have to run the HelloWorld at the directory that we store its class file
everytime?". The answer is NO. We can run the HelloWorld from anywhere as long as we still
include the package world in the CLASSPATH. For example,

C:\>set CLASSPATH=.;C:\;

C:\>set CLASSPATH // see what we have in CLSSPATH


CLASSPATH=.;C:\;

C:\>cd world

C:\world>java world.HelloWorld
Hello World

C:\world>cd ..

C:\>java world.HelloWorld
Hello World

Subpackage (package inside another package)


Assume we have another file called HelloMoon.java. We want to store it in a subpackage "moon",
which stays inside package world. The HelloMoon class should look something like this:

package world.moon;

public class HelloMoon {


private String holeName = "rabbit hole";

public getHoleName() {
return hole;
}

public setHole(String holeName) {


this.holeName = holeName;
}
}

If we store the package world under C: as before, the HelloMoon.java would be


c:\world\moon\HelloMoon.java as shown in Figure 4 below:

Figure 4. HelloMoon in world.moon package


Although we add a subpackage under package world, we still don't have to change anything in
our CLASSPATH. However, when we want to reference to the HelloMoon class, we have to use
world.moon.HelloMoon as its fully-qualified class name.

How to use package


There are 2 ways in order to use the public classes stored in package.
1. Declare the fully-qualified class name. For example,

...
world.HelloWorld helloWorld = new world.HelloWorld();
world.moon.HelloMoon helloMoon = new world.moon.HelloMoon();
String holeName = helloMoon.getHoleName();
...
2) Use an "import" keyword:

import world.*; // we can call any public classes inside the world package
import world.moon.*; // we can call any public classes inside the world.moon
package
import java.util.*; // import all public classes from java.util package
import java.util.Hashtable; // import only Hashtable class (not all classes
in java.util package)
Thus, the code that we use to call the HelloWorld and HelloMoon class should be

...
HelloWorld helloWorld = new HelloWorld(); // don't have to explicitly
specify world.HelloWorld anymore
HelloMoon helloMoon = new HelloMoon(); // don't have to explicitly specify
world.moon.HelloMoon anymore
...
Note that we can call public classes stored in the package level we do the import only. We can't use any
classes that belong to the subpackage of the package we import. For example, if we import package
world, we can use only the HelloWorld class, but not the HelloMoon class.

Using classes stored in jar file


Jar files are the place where we put a lot of files to be together. We compress these files and make them
as a single bundle. Jar files may also include directories, subdirectories to represent class and package
hierachy. Normally, we can see what is inside a jar file by using the command jar -tvf
fileName.jar as shown in Figure 5:
Figure 5. JSDK package viewed by jar -tvf jsdk.jar command

From figure 5 we see that there is a class called javax.servlet.http.Cookie. We can call this
class by

import javax.servlet.http.Cookie; // import only Cookie class or


import javax.servlet.http.*; // import the whole javax.servlet.http package

But we have to include this package in the CLASSPATH as well.

set CLASSPATH=.;D:\JSDK2.0\lib\jsdk.jar;
Note that if the package is stored inside a jar file, we have to include the jar file with its extension (.jar)
in the CLASSPATH. However, if the package is a plain directory, we just put the name of directory into
the CLASSPATH.

Naming a Package
With programmers worldwide writing classes and interfaces using the Java programming
language, it is likely that many programmers will use the same name for different types. In fact,
the previous example does just that: It defines a Rectangle class when there is already a
Rectangle class in the java.awt package. Still, the compiler allows both classes to have the
same name if they are in different packages. The fully qualified name of each Rectangle class
includes the package name. That is, the fully qualified name of the Rectangle class in the
graphics package is graphics.Rectangle, and the fully qualified name of the Rectangle class
in the java.awt package is java.awt.Rectangle.
This works well unless two independent programmers use the same name for their packages.
What prevents this problem? Convention.

Naming Conventions

Package names are written in all lower case to avoid conflict with the names of classes or
interfaces.

Companies use their reversed Internet domain name to begin their package names—for example,
com.example.mypackage for a package named mypackage created by a programmer at
example.com.

Name collisions that occur within a single company need to be handled by convention within
that company, perhaps by including the region or the project name after the company name (for
example, com.example.region.mypackage).

Packages in the Java language itself begin with java. or javax.

In some cases, the internet domain name may not be a valid package name. This can occur if the
domain name contains a hyphen or other special character, if the package name begins with a
digit or other character that is illegal to use as the beginning of a Java name, or if the package
name contains a reserved Java keyword, such as "int". In this event, the suggested convention is
to add an underscore. For example:

Legalizing Package Names

Domain Name Package Name Prefix

hyphenated-name.example.org org.example.hyphenated_name

example.int int_.example

123name.example.com com.example._123name

Using Package Members


The types that comprise a package are known as the package members.

To use a public package member from outside its package, you must do one of the following:

 Refer to the member by its fully qualified name


 Import the package member
 Import the member's entire package
Each is appropriate for different situations, as explained in the sections that follow.

Referring to a Package Member by Its Qualified Name

So far, most of the examples in this tutorial have referred to types by their simple names, such as
Rectangle and StackOfInts. You can use a package member's simple name if the code you are
writing is in the same package as that member or if that member has been imported.

However, if you are trying to use a member from a different package and that package has not
been imported, you must use the member's fully qualified name, which includes the package
name. Here is the fully qualified name for the Rectangle class declared in the graphics
package in the previous example.

graphics.Rectangle

You could use this qualified name to create an instance of graphics.Rectangle:

graphics.Rectangle myRect = new graphics.Rectangle();

Qualified names are all right for infrequent use. When a name is used repetitively, however,
typing the name repeatedly becomes tedious and the code becomes difficult to read. As an
alternative, you can import the member or its package and then use its simple name.

Importing a Package Member

To import a specific member into the current file, put an import statement at the beginning of
the file before any type definitions but after the package statement, if there is one. Here's how
you would import the Rectangle class from the graphics package created in the previous
section.

import graphics.Rectangle;

Now you can refer to the Rectangle class by its simple name.

Rectangle myRectangle = new Rectangle();

This approach works well if you use just a few members from the graphics package. But if you
use many types from a package, you should import the entire package.

Importing an Entire Package

To import all the types contained in a particular package, use the import statement with the
asterisk (*) wildcard character.

import graphics.*;
Now you can refer to any class or interface in the graphics package by its simple name.

Circle myCircle = new Circle();


Rectangle myRectangle = new Rectangle();

The asterisk in the import statement can be used only to specify all the classes within a package,
as shown here. It cannot be used to match a subset of the classes in a package. For example, the
following does not match all the classes in the graphics package that begin with A.

// does not work


import graphics.A*;

Instead, it generates a compiler error. With the import statement, you generally import only a
single package member or an entire package.

Note: Another, less common form of import allows you to import the public nested classes of an
enclosing class. For example, if the graphics.Rectangle class contained useful nested classes, such
as Rectangle.DoubleWide and Rectangle.Square, you could import Rectangle and its nested
classes by using the following two statements.

import graphics.Rectangle;
import graphics.Rectangle.*;
Be aware that the second import statement will not import Rectangle.

Another less common form of import, the static import statement, will be discussed at the end of this
section.

For convenience, the Java compiler automatically imports three entire packages for each source
file: (1) the package with no name, (2) the java.lang package, and (3) the current package (the
package for the current file).

Apparent Hierarchies of Packages

At first, packages appear to be hierarchical, but they are not. For example, the Java API includes
a java.awt package, a java.awt.color package, a java.awt.font package, and many others
that begin with java.awt. However, the java.awt.color package, the java.awt.font
package, and other java.awt.xxxx packages are not included in the java.awt package. The
prefix java.awt (the Java Abstract Window Toolkit) is used for a number of related packages to
make the relationship evident, but not to show inclusion.

Importing java.awt.* imports all of the types in the java.awt package, but it does not import
java.awt.color, java.awt.font, or any other java.awt.xxxx packages. If you plan to use the
classes and other types in java.awt.color as well as those in java.awt, you must import both
packages with all their files:

import java.awt.*;
import java.awt.color.*;

Name Ambiguities

If a member in one package shares its name with a member in another package and both
packages are imported, you must refer to each member by its qualified name. For example, the
graphics package defined a class named Rectangle. The java.awt package also contains a
Rectangle class. If both graphics and java.awt have been imported, the following is
ambiguous.

Rectangle rect;

In such a situation, you have to use the member's fully qualified name to indicate exactly which
Rectangle class you want. For example,

graphics.Rectangle rect;

The Static Import Statement

There are situations where you need frequent access to static final fields (constants) and static
methods from one or two classes. Prefixing the name of these classes over and over can result in
cluttered code. The static import statement gives you a way to import the constants and static
methods that you want to use so that you do not need to prefix the name of their class.

The java.lang.Math class defines the PI constant and many static methods, including methods
for calculating sines, cosines, tangents, square roots, maxima, minima, exponents, and many
more. For example,

public static final double PI


= 3.141592653589793;
public static double cos(double a)
{
...
}

Ordinarily, to use these objects from another class, you prefix the class name, as follows.

double r = Math.cos(Math.PI * theta);

You can use the static import statement to import the static members of java.lang.Math so that
you don't need to prefix the class name, Math. The static members of Math can be imported either
individually:

import static java.lang.Math.PI;


or as a group:

import static java.lang.Math.*;

Once they have been imported, the static members can be used without qualification. For
example, the previous code snippet would become:

double r = cos(PI * theta);

Obviously, you can write your own classes that contain constants and static methods that you use
frequently, and then use the static import statement. For example,

import static mypackage.MyConstants.*;

Note: Use static import very sparingly. Overusing static import can result in code that is difficult to read
and maintain, because readers of the code won't know which class defines a particular static object.
Used properly, static import makes code more readable by removing class name repetition.

To create a package for a type, put a package statement as the first statement in the source file
that contains the type (class, interface, enumeration, or annotation type).

To use a public type that's in a different package, you have three choices: (1) use the fully
qualified name of the type, (2) import the type, or (3) import the entire package of which the type
is a member.

The path names for a package's source and class files mirror the name of the package.

You might have to set your CLASSPATH so that the compiler and the JVM can find the .class
files for your types.

Attribute
A single piece of information that represents a property present in all instances of a class.
An attribute is often modeled as a variable in a class.
Byte
The amount of memory space used to store one ASCII character, which is usually 8 bits.
A bit is the smallest unit of information a computer can hold; short for binary digit, the
value can be either one or zero.
Component
A piece of software with a clear function that can be isolated and replaced by another
component with equivalent functionality.
Function
A method that performs some form of processing in order to return a result. For example,
a function to calculate the sum of two integers.
Input
Something put into a system or expended in its operation to achieve output or a result.
Library
A library is a collection of subprograms used to develop software. Libraries are
distinguished from executables in that they are not independent programs.
Namespace
A scoping construct to subdivide the set of names and their visibility within a system. In
many languages, this is tied to other computational constructs, eg, classes, procedures,
modules, packages. A mechanism used to resolve naming conflicts.
Performance
A major factor in determining the overall productivity of a system, performance is
primarily tied to availability, throughput and response time.
Statement
An entity in a programming language which is typically the smallest indivisible unit of
execution.
Sub-class
A class that is an extension of another class and inherits public and protected variables
and methods from the other class. Also known as a derived class.
reating Packages

Creating a Java Package is relatively simple but may seem a bit confusing for people who have
not done it before. There are two fundamental requirements for a package to exist:

 The package must contain one or more classes or interfaces. This implies that a package cannot
be empty.
 The classes or interfaces that are in the package must have their source files in the same
directory structure as the name of the package.

Naming Packages

Since packages are used to create namespaces that are used to prevent the problem of name
conflicts, namespaces must be unique. This means that package names must be unique. Naming
a package is therefore a very important aspect of creating a package.

Often organizations that are involved in software development will use their organi ation's
domain name, since domain names by definition are unique. The domain name is inverted to
make it easier to read. Good examples can be found from looking at the source code of the
Apache Software Foundation, whose domain name is www.apache.org. All their code is placed
into packages that have names beginning with org.apache.

Since the Apache Software Foundation has a number of sub-projects, each with its own web
address, the project name is also used in the package name. The Ant project can be found at
http://ant.apache.org, and it should be no surprise that their code is in the packages with names
beginning with org.apache.ant.

When naming your package you should take your inverted domain name, if you have one, and
add the project name to it. This will ensure that you have a unique package name, since it is
highly unlikely that your organization is working on two projects that have the exact same name.
As an example: com.mycompany.myproject

Some companies have decided to drop the top level domain (com, org, net, ...) from their
package names for the sake of brevity, this is still perfectly acceptable: mycompany.mypackage

Declaring Package Members

The first thing to do when creating a package is to decide which classes and interfaces should
belong to that package. Once you have decided that, you need to specify this by adding a
package declaration to the source file of each class and interface that is a part of the package.

The declaration is simple, you use the package keyword followed by the package name. This
declaration comes right at the top of the source file, before any import statements.

/*
* File comments...
*/

package com.mycompany.myproject;

import java.util.*;

class MyClass {

Source and Class File Organization

One of the requirements for a package is that the source file should be contained in a directory
structure that resembles the name of the package. This is simply creating a set of directories with
the names given in the package name.

Take the package name and split it up according to where the periods (.) occur, for example,
com.mycompany.myproject can easily be split up into three components, namely: com,
mycompany and myproject. These will be the three directories that you create. The first directory
will be the com directory and within this directory you will create a sub directory namely the
mycompany directory and within that directory a sub directory, namely the myproject directory.

Finally, all the source files that are part of the package will go into the myproject directory.

It is typical in many java project to have the source code go into a src directory and when it is
compiled, the resulting byte code goes into a classes directory. The package directories will
therefore go into the src directory. As an example, consider a class named MyClass in the
package named com.mycompany.myproject and all source code in the src directory. The
following picture depicts this situation clearly:
Compiling The Package

At first it may seem like a nightmare trying to compile the package, especially having the
resulting class files occur in the classes directory, but it can be achieved using a single command.
You don't even need all the package directories under the classes directory since they will be
created in the compilation.

To try this out, create a test directory and all the sub directories required:

mkdir test
mkdir test\src
mkdir test\classes
mkdir test\src\com
mkdir test\src\com\mycompany
mkdir test\src\com\mycompany\myproject

Now create the MyClass source file named MyClass.java in the


test\src\com\mycompany\myproject directory.

/* MyClass.java
* Author: Trevor Miller
*/
package com.mycompany.myproject;
public class MyClass {

Change into the test directory and compile the package:

cd test
javac -d ./classes/ ./src/com/mycompany/myproject/*.java

If you take a look in the classes directory, you will find the exact same directory structure as in
the src directory. You'll also find a MyClass.class file in the
test\classes\com\mycompany\mypackage directory. This is good as it allows you to keep your
source and class files separate and provides greater control over your files.

Using Packages

Once you have created your package you may want to use it in your program or you may wish to
use another programmer's package or the packages in the Java API. There are three ways of
using the resources in a package; inline package member declarations, importing only the
package member that you want and importing the entire package.

Inline Member Declarations

In this approach you simply declare the package member you wish to use with its fully qualified
package name. As an example, suppose you wish to use the Vector class in the java.util package.
You can easily declare a vector using java.util.Vector vector;

When you initialize the object by calling its constructor, you will again have to use the fully
qualified package name.

class Test {
java.util.Vector vector;

Test() {
vector = new java.util.Vector();
}
}

Importing a Single Package Member

Using the inline declaration works well if you only use it a few times in your source code, but it
can become a pain to type the fully qualified package name if you use it often. Instead you want
to do this once and only once, and from then on, simply use the member's name wherever you
need it.

This is easily achieved using an import statement in which the import keyword is followed by the
fully qualified name of the member you wish to use. Consider the example given previously, but
revised to use this method:

import java.util.Vector;
class Test {
Vector vector;

Test() {
vector = new Vector();
}
}

Importing an Entire Package

It may be that you use a number of members from a package and end up with a large number of
import statements. As an example consider the following:

import java.util.Vector;
import java.util.LinkedList;
import java.util.Hashtable
import java.util.Stack
import java.util.Set

class Test {
...
}

This can become messy quite quickly, and you would like to get away from this. The answer is
to simply import the entire package, again using the import statement but instead of declaring the
member you use a wildcard symbol to indicate that everything should be imported. The wildcard
symbol is an asterisk (*), using this method you can replace all the import statements of the
previous example with simply one import statement.

import java.util.*;

class Test {
...
}

As you can see, this is much cleaner but it does have its limitations. If the package is very large
and you import everything in the package, this will impact the performance of your program.
You should consider carefully whether greater clarity in your code and ease of writing the code
outweighs the addition of some overhead to the performance of your application.
Summary

Packages are a great way to organize your source code and split source code from byte code
(class files). Understanding how packages work is vital to writing quality software.

Exercise Set
Multiple Choice

1. Namespaces are used to:


1. Control access to classes.
2. Resolve naming conflicts among programmers.
3. Bundle a set of classes together.
2. Which is not a benefit of using packages?
1. Finding the classes you want is difficult.
2. Access protection.
3. Separation of source and class files.
3. To create a package named "za.co.nephila.maculata" you would use which statement?
1. package maculata
2. package nephila.maculata
3. package za.co.nephila.maculata
4. To import the ChatServer member of the Maculata package (za.co.nephila.maculata) you
would use:
1. import maculata.*;
2. import za.co.nepihla.maculata.*;
3. import za.co.nephila.maculata.ChatServer;
5. The classes of the Maculata package (za.co.nephila.maculata) will be in which directory?
1. /Maculata/classes
2. /Maculata/classes/za/co/nephila/maculata
3. /Maculata/src/za/co/nephila/maculata

Example 1

We shall write a class called Circle in package com.yyy. It is a good practice to store the source
codes and the classes in separate directories, to facilitate the distribution of classes without the
source codes. Suppose that we save the source as
d:\myJavaProject\src\com\yyy\Circle.java, and the compiled class as
d:\myJavaProject\classes\com\yyy\Circle.class. Let's write the source as follows:

// d:\myJavaProject\src\com\yyy\Circle.java
package com.yyy;
public class Circle {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
}

To compile the source using JDK, we need to use the -d option to specify the package base
directory of the compiled class d:\myJavaProject\classes as follows (-d defaulted to the
current directory):

> javac -d d:\myJavaProject\classes d:\myJavaProject\src\com\yyy\Circle.java

The compiled class will be kept in d:\myJavaProject\classes\com\yyy\Circle.class.


Directory "com.yyy" will be created automatically. Instead of absolute path, we could also use
relative path.

Let's write a test program to use this Circle class. Suppose that TestCircle.java is saved in
d:\myOtherProject.

// d:\myOtherProject\TestCircle.java
import com.yyy.Circle;
public class TestCircle {
public static void main(String[] args) {
Circle c = new Circle(1.23);
System.out.println(c.getRadius());
}
}
If we compile TestCircle.java from the directory d:\myOtherProject, we will get a error
message, as the compiler cannot find the com.yyy.Circle class.

d:> cd \myOtherProject

d:\myOtherProject> javac TestCircle.java


TestCircle.java:1: package com.yyy does not exist
import com.yyy.Circle;
^

We need to use the -cp (or -classpath) option to specify the base directory of the package
com.yyy, in order to locate com.yyy.Circle.

d:\myOtherProject> javac -cp d:\myJavaProject\classes TestCircle.java

To run the TestCircle, we again get a error, as JRE cannot find the com.yyy.Circle.

d:\myOtherProject> java TestCircle


Exception in thread "main" java.lang.NoClassDefFoundError: com/yyy/Circle

Let include the base directory of the package com.yyy in the classpath (to locate
com.yyy.Circle):
d:\myOtherProject> java -cp d:\myJavaProject\classes TestCircle
Exception in thread "main" java.lang.NoClassDefFoundError: TestCircle

But now, the JRE can't even find the TestCircle class, which is located in the current directory.
This is because if CLASSPATH is not explicitly set, it defaulted to the current directory. However,
if CLASSPATH is explicitly set, it does not include the current directory unless the current
directory is included. Hence, we need to include current directory (denoted as '.') in the
CLASSPATH, together with the base directory of package com.yyy, separated by ';', as follows:

d:\myOtherProject> java -cp .;d:\myJavaProject\classes TestCircle


1.23

Example 2

Suppose that the TestCircle class in Example 1 in defined in a package com.abc, and save as
d:\myOtherProject\src\com\abc\TestCircle.java.

// d:\myOtherProject\src\com.abc\TestCircle.java
package com.abc;
import com.yyy.Circle;
public class TestCircle {
......
}

Suppose the compiled class is to be kept as


d:\myOtherProject\classes\com\abc\TestCircle.class.

-- To compile TestCircle.java, set the current directory and use relative


paths for TestCircle.
d:> cd \myOtherProject
d:\myOtherProject> javac -d classes -cp d:\myJavaProject\classes
src\com\abc\TestCircle.java
-- To run TestCircle, need to include the base directory of TestCircle and
Circle in classpath.
-- Also need to use the fully-qualified name (package name plus class name)
for TestCircle
d:\myOtherProject> java -cp classes;d:\myJavaProject\classes
com.abc.TestCircle

Another Example

In this example, we have more than one classes in the package and the classes reference each
others. For example, the package com.zzz.project1.subproject2 has two classes: MyClass3
and MyClass4, defined as follows:

package com.zzz.project1.subproject2;
public class MyClass3 {
private MyClass4 myClass4;
public MyClass3 () { // constructor
System.out.println("MyClass3 constructed");
myClass4 = new MyClass4(); // use MyClass4 in the same package
}
// main() included here for testing
public static void main(String[] args) {
new MyClass3();
}
}
package com.zzz.project1.subproject2;
public class MyClass4 { // constructor
public MyClass4() {
System.out.println("MyClass4 constructed");
}
}

Case 1: Source and class files in the same directory

Suppose that we keep the source and class files in the same directory, says,
$BASE_DIR\com\zzz\project1\subproject2. Note that you have to adhere to the sub-
directory structure specified in the package name for keeping the classes. I assume that the
CLASSPATH includes the current working directory.

To compile all the source files:

> cd $BASE_DIR
> javac com\zzz\project1\subproject2\*.java

The resultant class files will be placed in the same directory as the source files.

To execute the MyClass3, you need to issue the fully-qualified class name:

> cd $BASE_DIR
> java com.zzz.project1.subproject2.MyClass3

NOTES:

 To compile the program, you specify the directory path using directory separator '\'.
 To execute the class, you specify the fully-qualified class name using the dot '.'.

Alternatively, you can launch the class from any directory, provided that the $BASE_DIR is
included in the CLASSPATH environment variable. You can also use command-line option -
classpath or -cp to specify CLASSPATH used for this command:

> java –cp $BASE_DIR com.zzz.project1.subproject2.MyClass3

Case 2: Source and class files in separate directories

Suppose that you decided to keep the source files and classes in separate directories (for
distribution of classes without the sources), and the directory structure of your source files and
classes is as follows:
To compile the source files and place the classes in the desired directory, you can use the "-d"
(for destination) command-line option of the Java compiler, which specifies the location of the
compiled classes. You also need to specify the CLASSPATH of the classes, as MyClass3 uses
MyClass4, as follows:

> cd $SRC_BASE_DIR\zzz\project1\subproject2
> javac –d $CLASS_BASE_DIR -classpath .;$CLASS_BASE_DIR *.java
// try omitting the classpath and compile just MyClass3 which uses MyClass4
> javac –d $CLASS_BASE_DIR MyClass3.java

The sub-directory structure corresponding to the package name for the classes will be created
automatically if it does not already exist. In summary, during the compilation, you need to set
both -d (for destination of the classes), and -classpath (if one class references other classes in
the package).

In the above example, the source directory $SRC_BASE_DIR is "c:\javaproject\src" and the
classes' base directory $CLASS_BASE_DIR is "c:\javaproject\classes"

To execute the MyClass3:

> cd $CLASS_BASE_DIR
> java com.zzz.project1.subproject2.MyClass3
Using IDE

Managing packages and CLASSPATH yourself with obly JDK is troublesome. IDE such as
Eclipses and Netbeans could manage the packages and CLASSPATH for you!!

The Default Package

Every Java class must belong to a package. You can explicitly name the package by providing a
package statement in the beginning of the source file. If the package statement is omitted, the
class belongs to the so-called default package, with no sub-directory structure. Use of default
package is not recommended other than writing toy program and for quick testing.

CLASSPATH - For Locating Classes

CLASSPATH is an environment variable (i.e., global variables of the operating system available to
all the processes) needed for the Java compiler and runtime to locate the Java packages used in a
Java program. (Why not call PACKAGEPATH?) This is similar to another environment variable
PATH, which is used by the CMD shell to find the executable programs.

CLASSPATH can be set in one of the following ways:

1. CLASSPATH can be set permanently in the environment: In Windows, choose control panel ⇒
System ⇒ Advanced ⇒ Environment Variables ⇒ choose "System Variables" (for all the users) or
"User Variables" (only the currently login user) ⇒ choose "Edit" (if CLASSPATH already exists) or
"New" ⇒ Enter "CLASSPATH" as the variable name ⇒ Enter the required directories and JAR
files (separated by semicolons) as the value (e.g.,
".;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar"). Take note that you
need to include the current working directory (denoted by '.') in the CLASSPATH.

To check the current setting of the CLASSPATH, issue the following command:

> SET CLASSPATH

2. CLASSPATH can be set temporarily for that particular CMD shell session by issuing the following
command:
3. > SET CLASSPATH=.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar
4. Instead of using the CLASSPATH environment variable, you can also use the command-line
option -classpath or -cp of the javac and java commands, for example,
5. > java –classpath c:\javaproject\classes
com.abc.project1.subproject2.MyClass3

How Classes are Found?


(Read "How classes are found" at the JDK documentation's main page.)

The Java Virtual Machine (JVM) searches for and loads classes in this order:
1. Bootstrap Classes: include rt.jar (runtime), and other classes specified in the
sun.boot.class.path system property, which could include i18n.jar
(internationalization), sunrsasign.jar, jsse.jar, jce.jar, charsets.jar, and
jre/classes.
2. Extension Classes via Java Extension mechanism: classes bundled as JAR file and kept in the
"$JAVA_HOME/jre/lib/ext" directory.
3. User Classes: located via –classpath or –cp command-line option or CLASSPATH environment
variable.

Normal users need not concern about bootstrap and extension classes. User classes are found
though the so-called user class path - a list of directories and JAR files which contain class files.
The directories and JAR files in the user class path are separated with a semi-colon ';' for
Windows systems, or colon ':' for UNIX systems. The user class path is kept in the System
Property java.class.path. The value is obtained from:

1. The default value '.' or current working directory.


2. The value of the CLASSPATH environment variable, which overrides the default value.
3. The value of –classpath or -cp command-line option, which overrides both the default value
and the CLASSPATH value.
4. The JAR files in the -jar command line option, which overrides all other values.

[How about java.lang, and classes in the same package? What is the order?]

Exceptions
An exception is a problem that arises during the execution of a program. An exception can occur
for many different reasons, including the following:

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

To understand how exception handling works in Java, you need to understand the three
categories of exceptions:

 Checked exceptions: A checked exception is an exception that is typically a user error or


a problem that cannot be foreseen by the programmer. For example, if a file is to be
opened, but the file cannot be found, an exception occurs. These exceptions cannot
simply be ignored at the time of compilation.
 Runtime exceptions: A runtime exception is an exception that occurs that probably
could have been avoided by the programmer. As opposed to checked exceptions, runtime
exceptions are ignored at the time of compliation.
 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, that means exceptional errors. Actually exceptions are used for handling errors
in programs that occurs during the program execution. During the program execution if
any error occurs and you want to print your own message or the system message about
the error then you write the part of the program which generate the error in the try{}
block and catch the errors using catch() block. Exception turns the direction of normal
flow of the program control and send to the related catch() block. Error that occurs during
the program execution generate a specific object which has the information about the
errors occurred in the program.
 In the following example code you will see that how the exception handling can be done
in java program. This example reads two integer numbers for the variables a and b. If you
enter any other character except number ( 0 - 9 ) then the error is caught by
NumberFormatException object. After that ex.getMessage() prints the information about
the error occurring causes.
 Code of the program :

import java.io.*;

public class exceptionHandle{


public static void main(String[] args) throws Exception{
try{
int a,b;
BufferedReader in =
new BufferedReader(new InputStreamReader(System.in));
a = Integer.parseInt(in.readLine());
b = Integer.parseInt(in.readLine());
}
catch(NumberFormatException ex){
System.out.println(ex.getMessage()
+ " is not a numeric value.");
System.exit(0);
}
}
}

The hierarchy of exception classes commence from Throwable class which is the base class
in java.lang. This class can be instantiated and thrown by the program.
Exception Classes

The hierarchy of exception classes commence from Throwable class which is the base class for
an entire family of exception classes, declared in java.lang package as java.lang.Throwable. A
throwable contains a snapshot of the execution stack at the time it was created and also a
message string that gives more information about the error. This class can be instantiated and
thrown by the program. The throwable class is further divided into two subclasses :-

1. Exceptions - Exceptions are thrown if any kind of unusual condition occurs that can be
caught. Sometimes it also happens that the exception could not be caught and the
program may get terminated. Remember that they are a member of Exception family and
can be type of Checked or Unchecked exception.
2. Errors - When any kind of serious problem occurs which could not be handled easily
like OutOfMemoryError then an error is thrown. Well, errors are not something which
is thrown by you rather they are thrown by the Java API or by the Java virtual machine
itself i.e. only the exceptions are thrown by your code and not the errors. Also Remember
that they are a member of Error family.

The exception classes can be explained as well seeing the exception hierarchy structure:

The java.lang package defines several classes and exceptions. Some of these classes are not
checked while some other classes are checked.
EXCEPTIONS DESCRIPTION CHECKED UNCHECKED
Arithmetic errors
ArithmeticException such as a divide - YES
by zero
Arrays index is
ArrayIndexOutOfBoundsException not within - YES
array.length
Related Class
ClassNotFoundException YES -
not found
InputOuput field
IOException YES -
not found
Illegal argument
IllegalArgumentException when calling a - YES
method
One thread has
been interrupted
InterruptedException YES -
by another
thread
Nonexistent
NoSuchMethodException YES -
method
Invalid use of
NullPointerException - YES
null reference
Invalid string for
NumberFormatException conversion to - YES
number

As you have come to know that exceptions are Objects that means an object is thrown when you
throw an exception. Moreover only those objects could be thrown whose classes are derived
from Throwable.

It is interesting to note here that the objects of your own design could also be thrown provided
that they should be the subclass of some member of the Throwable family. Also the throwable
classes which are defined by you must extend Exception class.

It depends upon the situation that whether to use an existing exception class from java.lang or
create any of your own. Such as IllegalArgumentException, a subclass of RuntimeException
in java.lang can be thrown if any method with an invalid argument is thrown by you. On the
other hand you need not to worry if you wish to impart some more information about any
unusual condition other than a class from java.lang because it will be indicated by the class of
exception object itself.

For example, if a thrown exception object has class IllegalArgumentException, that indicates
someone passed an illegal argument to a method. Sometimes you will want to indicate that a
method encountered an abnormal condition that isn't represented by a class in the Throwable
family of java.lang.
For instance, lets tweak an example below that demonstrates the exceptional conditions that
might occur while driving a car.

// In Source Packet in file


except/ex1/SpeedException.java
class SpeedException extends Exception {
}
// In Source Packet in file
except/ex1/VeryFastException.java
class VeryFastException extends
SpeedException {
}
// In Source Packet in file
except/ex1/VerySlowException.java
class VerySlowException extends
SpeedException {
}

Lets tweak the diagram below.

It is clear from the above program that there is something abnormal with the speed of the car i.e.
either it is very fast or it is very slow. Hence two exceptions are thrown by the program -
VeryFastException and VerySlowException. To be more precise the SpeedException family
specifies three new exceptions thrown by the program which indicate some abnormal conditions.
That is the SpeedException specifies that there is something unusual with the speed;
VeryFastException and VerySlowException specifies the abnormal conditions of the speed.

NOTE: The SpeedException extends Exception only and not the Throwable or Error class.
Catching and Handling Exceptions:

Java Catching and Handling Exceptions

The various keywords for handling exceptions are below.

 try
 catch
 finally
 throw
 throws

The three exception handler components are used to catch and handle the exceptions. These are
try, catch and finally clause. The mechanism to catch an exception in Java is to use try and
catch block. Every catch block can handle only one type of exception however you can use more
than one catch clause in a single try block. Simply a statement is surrounded by the try block that
may cause the exception to occur. Then the try block is followed by the catch block. And if the
exception occurs then this catch block specifies a code that should be executed.

Using try and catch:-

The syntax for the usage of try, catch and finally block is given below.

try{
???
???
}
catch(<exceptionclass1> <obj1>){
???
???
}
finally{
???
???
}

For using an exception handler in an application, the first step we need to do is to enclose the
code that is likely to generate an exception inside a try block. If an exception occurs in the try
block then it is handled by the exception handler associated with it. For doing this we need to
have one or more catch blocks after the try block, where each catch block acts as an exception
handler and can handle the type of exception indicated by its arguments.

Lets have a look at the example which shows the implementation of the try, catch and finally
block. Here we have used "fis = new FileInputStream (new File (args[0]));" which throws an
exception if we write a name of a file which doesn't exist as shown in the output.

import java.io.*;

class Test{
public static void main(String args[])throws
IOException {
FileInputStream fis=null;
try{
fis = new FileInputStream (new File (args[0]));
}
catch (FileNotFoundException e){
System.out.println("File not found!");
}
finally{
fis.close();
}
}
}

Output of program:

C:\Roseindia\vinod\Exception>javac
Test.java

C:\Roseindia\vinod\Exception>java
Test
File not found!

Download this example

The code which is to be executed in a try block indicates that it will throw an exception. And if
the exception occurs then the runtime system checks whether the exception thrown by try block
matches to the one in catch clause or not. If yes, then the code within the catch clause gets
executed which actually handles the exception.

Using final: It is always a good practice to use finally clause after the try and catch block
because the finally block always executes even if an unexpected exception occurs i.e. whether or
not an exception thrown. The finally block executes if and only if the try block exits. Other than
exception handling the finally clause helps you in avoiding any cleanup code accidentally
bypassed by a return etc. The statements within the finally block gets executed by the the
runtime system without taking care of what happens within the try block.

There are two steps to use the finally clause:

 First, you need to enclose the code in a try block that has multiple exit points.
 Secondly after the try block exits place the code that must be executed in a finally clause.

Same way we have used the finally block which will execute after the try and catch block.

import java.io.*;

class Test{
public static void main(String args[]){
FileInputStream fis=null;
try {
fis = new FileInputStream (new File (args[0]));
int ch;
while ((ch = fis.read()) != -1){
System.out.print ((char) ch);
}
}
catch (FileNotFoundException e){
System.out.println("File not found!");
}
catch (IOException e){
System.out.println("Unable to read file!");
}
finally{
System.out.println();
System.out.println("In finally.");
try{
if(fis!=null){
fis.close();
}
}
catch (IOException ioe){
System.out.println("In finally.");
}
}
}
}

Output of program:
C:\Roseindia\vinod\Exception>javac
Test.java

C:\Roseindia\vinod\Exception>java
Test abc
File not found!

In finally.

Download this example

Using throws: The other way to handle an exception is using the throws clause. When you call a
method from the java API that throws a checked exception, you must either throw the exception
or catch it. If you decide that you can't handle the exception properly, then the exception can be
declared to the method header using the throws keyword followed by the class name of the
exception.

You might have come across the throws IOException clause in the method header. For example
System.in.read() will give a compile error for IOException. Add the throws clause to the
surrounding method to pass the error up to the next level (or else write your own catch/try
handler). This clause is placed between the parameter list and the starting of the opening brace of
the method. We use this clause when we know that a particular exception may occur. Then
instead of terminating the program the compiler throws the exception.

While the throw keyword (note the singular form) is used to force an exception. It can also pass
a custom message to your exception handling module. for example:-

throw new FileNotFoundException("Could not find books.txt");

The syntax for coding the throws clause of a method is as:-

method declaration throws Exception1,[Exception2] .......{ }

Likewise we have used throws clause to the method header as "throws


FileNotFoundException,IOException " which throws an exception as shown in the output.

import java.io.*;

class Test3{
public static void main(String args[]) throws FileNotFoundException,IOException {
FileInputStream fis=null;
fis = new FileInputStream (new File (args[0]));
int ch;
while ((ch = fis.read()) != -1){
System.out.print ((char) ch);
}
fis.close();
}
}

Output of program:

C:\Roseindia\vinod\Exception>javac Test3.java

C:\Roseindia\vinod\Exception>java Test3
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 0
at Test3.main(Test3.java:6)

How to Throw Exceptions:


Before catching an exception it is must to be thrown first. This means that there should be
a code somewhere in the program that could catch the exception.

How to Throw Exceptions in Java

Before catching an exception it is must to be thrown first. This means that there should be a code
somewhere in the program that could catch the exception. We use throw statement to throw an
exception or simply use the throw keyword with an object reference to throw an exception. A
single argument is required by the throw statement i.e. a throwable object. As mentioned
earlier Throwable objects are instances of any subclass of the Throwable class.

throw new VeryFastException();

Note: The reference should be of type Throwable or one of its subclasses.

For instance the example below shows how to throw an exception. Here we are trying to divide a
number by zero so we have thrown an exception here as "throw new MyException("can't be
divided by zero");"

class MyException extends Exception {


public MyException(String msg){
super(msg);
}
}

public class Test {


static int divide(int first,int second) throws MyException{
if(second==0)
throw new MyException("can't be divided by zero");
return first/second;
}

public static void main(String[] args) {


try {
System.out.println(divide(4,0));
}
catch (MyException exc) {
exc.printStackTrace();
}
}
}

Output of program:

C:\Roseindia\vinod\Exception>javac
Test.java

C:\Roseindia\vinod\Exception>java
Test
MyException: can't be divided by
zero
at Test.divide(Test.java:10)
at Test.main(Test.java:15)

C:\Roseindia\vinod\Exception>

Difference between throw and throws keywords


Whenever we want to force an exception then we use throw keyword. the throw keyword (note
the singular form) is used to force an exception. It can also pass a custom message to your
exception handling module. Moreover throw keyword can also be used to pass a custom
message to the exception handling module i.e. the message which we want to be printed. For
instance in the above example we have used -

throw new MyException ("can't be divided by zero");

Whereas when we know that a particular exception may be thrown or to pass a possible
exception then we use throws keyword. Point to note here is that the Java compiler very well
knows about the exceptions thrown by some methods so it insists us to handle them. We can also
use throws clause on the surrounding method instead of try and catch exception handler. For
instance in the above given program we have used the following clause which will pass the error
up to the next level -

static int divide(int first,int second) throws MyException{

Handling Multiple Catch Clauses


So far we have seen how to use a single catch block, now we will see how to use more than one catch
blocks in a single try block.

Handling Multiple Catch Clauses

So far we have seen how to use a single catch block, now we will see how to use more than one
catch blocks in a single try block.In java when we handle the exceptions then we can have
multiple catch blocks for a particular try block to handle many different kind of exceptions that
may be generated while running the program i.e. you can use more than one catch clause in a
single try block however every catch block can handle only one type of exception. this
mechanism is necessary when the try block has statement that raise different type of exceptions.

The syntax for using this clause is given below:-

try{
???
???
}
catch(<exceptionclass_1> <obj1>){
//statements to handle the
exception
}

catch(<exceptionclass_2> <obj2>){
//statements to handle the
exception
}
catch(<exceptionclass_N> <objN>){
//statements to handle the
exception
}

When an exception is thrown, normal execution is suspended. The runtime system proceeds to
find a matching catch block that can handle the exception. If no handler is found, then the
exception is dealt with by the default exception handler at the top level.
Lets see an example given below which shows the implementation of multiple catch blocks for a
single try block.

public class Multi_Catch


{
public static void main (String args[])
{
int array[]={20,10,30};
int num1=15,num2=0;
int res=0;

try
{
res = num1/num2;
System.out.println("The result is" +res);

for(int ct =2;ct >=0; ct--)


{
System.out.println("The value of array are"
+array[ct]);
}

}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Error?. Array is out of
Bounds");
}

catch (ArithmeticException e)
{
System.out.println ("Can't be divided by Zero");
}

}
}

Output of the program:

C:\Roseindia\>javac Multi_Catch.java

C:\Roseindia\>java Multi_Catch

Can't be divided by Zero


In this example we have used two catch clause catching the exception
ArrayIndexOutOfBoundsException and ArithmeticException in which the statements that
may raise exception are kept under the try block. When the program is executed, an exception
will be raised. Now that time the first catch block is skipped and the second catch block handles
the error.

Download this program

Lets have an another output, in which the second catch block is skipped and the first catch block
handles the error.

public class Multi_Catch1


{
public static void main (String args[])
{
int array[]=new int [5];
int num1=15,num2=2;
int res=0;

try
{
res = num1/num2;
System.out.println("The result is" +res);

for(int ct =0;ct <=5; ct++)


{
array[ct] = ct * ct ;
}

}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Assigning the array
beyond the upper bound");
}

catch (ArithmeticException e)
{
System.out.println ("Can't be divided by
Zero");
}

}
}
Output of the program:

C:\Roseindia\>javac Multi_Catch.java

C:\Roseindia\>java Multi_Catch

Assigning the array beyond the


upper bound

Download this example

Handling the Unreachable Code Problem

The multiple catch blocks can generate unreachable code error i.e. if the first catch block
contains the Exception class object then the subsequent catch blocks are never executed. This is
known as Unreachable code problem. To avoid this, the last catch block in multiple catch
blocks must contain the generic class object that is called the Exception class. This exception
class being the super class of all the exception classes and is capable of catching any types of
exception. The generic Exception class can also be used with multiple catch blocks.

Take a look at the following example:

public class Generic_Excep


{
public static void main (String args[])
{
String str = "Exception" ;
int len=0;
try
{
StringBuffer sbuf = new StringBuffer(str);
len = str.length() ;
for(int ct=len;ct>=0;ct--)
{
System.out.print(sbuf.charAt(ct));
}
}
catch(Exception e)
{
System.out.println("Error...."+e);
}
}
}
Output of the program:

C:\Roseindia\>javac Generic_Excep.java

C:\Roseindia\>java Generic_Excep

Error....java.lang.StringIndexOutOfBoundsException:
String index out of range: 9

In this example we didn't specify that which one exception may occur during the execution of
program but here we are trying to access the value of an array that is out of bound still we don't
need to worry about handle the exception because we have used the Exception class that is
responsible to handle any type of exception.

Nested Try-Catch Blocks


In Java we can have nested try and catch blocks. It means that, a try statement can be
inside the block of another try. we can have nested try and catch blocks. It means that, a try
statement can be inside the block of another try. If an inner try statement does not have a
matching catch statement for a particular exception, the control is transferred to the next try
statement?s catch handlers that are expected for a matching catch statement. This continues until
one of the catch statements succeeds, or until all of the nested try statements are done in. If no
one catch statements match, then the Java run-time system will handle the exception.

The syntax of nested try-catch blocks is given below:

try {
try {
// ...
}
catch (Exception1 e)
{
//statements to handle the
exception
}
}
catch (Exception 2 e2)
{
//statements to handle the
exception
}
Lets have an example that uses the nested try-catch blocks

import java.io.*;
public class NestedTry{
public static void main (String args[])throws IOException {
int num=2,res=0;

try{
FileInputStream fis=null;
fis = new FileInputStream (new File (args[0]));
try{
res=num/0;
System.out.println("The result is"+res);
}
catch(ArithmeticException e){
System.out.println("divided by Zero");
}
}
catch (FileNotFoundException e){
System.out.println("File not found!");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Array index is Out of bound!
Argument required");
}
catch(Exception e){
System.out.println("Error.."+e);
}
}
}

Output of the program:

C:\Roseindia\>javac
NestedTry.java

C:\Roseindia\>java NestedTry

Array index is Out of bound!


Argument required

In this given example we have implemented nested try-catch blocks concept where an inner try
block is kept with in an outer try block, that's catch handler will handle the arithmetic exception.
But before that an ArrayIndexOutOfBoundsException will be raised, if a file name is not
passed as an argument while running the program. Now lets see, what will be the output if we
pass the file name student as an argument.

C:\Roseindia\>javac
NestedTry.java

C:\Roseindia\>java NestedTry
student.txt

File not found!

If the outer try block's statements run successfully then the inner try will
raise an ArithmeticException as:

C:\Roseindia\>javac
NestedTry.java

C:\Roseindia\>java NestedTry
student.txt

divided by Zero

Catching Normal Exceptions


The exceptions that are generated by methods are referred to as normal exceptions. We
have already learned that to catch an exception we use try and catch block.

The exceptions that are generated by methods are referred to as normal exceptions. We have
already learned that to catch an exception we use try and catch block.

try {
myTestException();
}
catch(ExceptionType1 e) {
System.out.println(e.getMessage());
}
catch(Exceptiontype2 e) {
System.out.println(e.getMessage());
}

The code above shows how to handle multiple exceptions. We have used myTestException();
method here which generates two different types of exceptions handled by separate catch clauses
in a unique manner. By comparing the exception type, the catch clauses are examined whenever
an exception occurs in a try block A match will occur whenever the type of exception is same as
that in catch clause or same as the subclass in the catch clause. Hence due to this multilevel catch
handlers can be provided which are based on more derived exception types. Lets see one more
example:

FileInputStream fis=null;
try{
fis = new FileInputStream (new File
(args[0]));
}
catch (FileNotFoundException e){
System.out.println("File not found!");
+ e.getMessage());
}

Here we have created a file input stream and the constructor which takes a file name to read from
will throw FileNotFoundException if the file couldn't be found. Within a try block an object is
created that handles the exception FileNotFoundException in a catch block as the constructor is
capable of throwing this exception.

Catching Runtime Exceptions

The exceptions which are not easily traced are known as Runtime Exceptions. For instance,

try {
int x = 50;
for (int i = 15; i >= 0; i--)
System.out.println(x / i);
}
catch(ArithmeticException e) {
System.out.println(e.getMessage());
}

The above code displays a for loop trying to divide a number by zero in its last iteration which
would result in runtime exception. We have used try block to handle this exception and a
corresponding handler by means of a catch clause. And if we won't handle the exception the
program will end up with the termination.

The disadvantage in handling the runtime exception is that we need to put the doubtful code
inside a try block. This approach sometimes causes a mess so its always better to avoid the
problems which land you up with the troubles.

Making Custom (User Define Exceptions)


So far you would have been known, how to be handled the exceptions in java =======

So far you would have been known, how to be handled the exceptions in java >>>>>>> 1.3 that
are thrown by the Java API but sometimes you may occasionally need to throw your own
exception i.e. if you encounter a situation where none of those exception describe your
exception accurately or if you can't find the appropriate exception in the Java API, you can code
a class that defines an exception that is more appropriate and that mechanism of handling
exception is called Custom or User Defined Exception.

In Java API all exception classes have two type of constructor. First is called default constructor
that doesn't accept any arguments. Another constructor accepts a string argument that provides
the additional information about the exception. So in that way the Custom exception behaves
like the rest of the exception classes in Java API.

There are two primary use cases for a custom exception.

 your code can simply throw the custom exception when something goes wrong.
 You can wrap an exception that provides extra information by adding your own
message.

The code of a Custom exception:

public class ExceptionClassName


extends Exception
{
public ExceptionClassName(){ }
public
ExceptionClassName(StringMessage)
{
super(message);
}
}

Lets see an example that has the implementation of User Define Exception:

import java.io.*;
import java.util.*;

class MyException extends Exception


{
private String nm="";
public String getMessage(String s)
{

nm=s;
return ("you are not permitted to enter inside "+nm);
}
}

public class ExcepDemo


{
public static void main(String args[])throws
MyException,IOException
{
String temp="";

try
{
String str="amit";
System.out.println("Enter the your name");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
temp=br.readLine();

if(!temp.equals(str))
throw new MyException();
else
System.out.println("Welcome to Rose India");
}
catch(MyException e)
{
System.err.println(e.getMessage(temp));
}
catch(Exception e){
System.err.println(e);
}
}
}

Output of the program:

C:\Roseindia\>javac
ExcepDemo.java

C:\Roseindia\>java
ExcepDemo

Enter the your name

nisha

you are not permitted to enter


inside nisha

C:\Roseindia\>java
ExcepDemo

Enter the your name

amit

Welcome to Rose India


In this example we have created own exception class as MyException that throws an exception
and a function with argument as getMessage that shows an exception message, if the user tries to
enter the another name which doesn't match with a particular predefined name. After throwing
exception the control will be transferred in the catch block to handle the exception.

Whenever in a program the first exception causes an another exception, that is termed as Chained
Exception. Java provides new functionality for chaining exceptions.

What are Chained Exceptions in Java?

Whenever in a program the first exception causes an another exception, that is termed as
Chained Exception. Java provides new functionality for chaining exceptions. Exception
chaining (also known as "nesting exception") is a technique for handling the exception, which
occur one after another i.e. most of the time is given by an application to response to an
exception by throwing another exception. Typically the second exception is caused by the first
exception. Therefore chained exceptions help the programmer to know when one exception
causes another.

The constructors that support chained exceptions in Throwable class are:

Throwable initCause(Throwable)
Throwable(Throwable)
Throwable(String, Throwable)
Throwable getCause()

The methods of the Throwable class are:

METHOD DESCRIPTION

Returns the exception followed by a message string (if


toString()
one exit) .

getMessage() Returns the message string of the Throwable object.

Returns the full name of the exception class and some


printStackTrace() additional information apart from the information of
first two method.

Returns the exception that caused the occurrence of


getCause()
current exception.

initCause() Returns the current exception due to the Throwable


constructors and the Throwable argument to initCause.

The syntax for using a chained exception is as follows in which a new TestException exception
is created with the attached cause when an IOException is caught. Thus the chain exception is
thrown to next level of exception handler.

try {
} catch (IOException e) {
throw new TestException("Other
IOException", e);
}

Lets see an example having the implementation of chained exceptions:

import java.io.*;
import java.util.*;
class MyException extends Exception{
MyException(String msg){
super(msg);
}
}
public class ChainExcep{
public static void main(String args[])throws MyException,
IOException{
try{
int rs=10/0;
}
catch(Exception e){
System.err.println(e.getMessage());
System.err.println(e.getCause());
throw new MyException("Chained
ArithmeticException");
}
}
}

Output of the Program:

C:\Roseindia\>javac ChainExcep.java
C:\Roseindia\>java javac ChainExcep

/ by zero
null
Exception in thread "main"
MyException: Chained
ArithmeticException
at
ChainExcep.main(ChainExcep.java:21)

This example has an user defined exception that throws an ArithmeticException and has been
thrown under the catch handler. After throwing an exception, the handler will execute the
statement of the catch block and then invoke the user defined constructor. Thus the
implementation of chained exception is very helpful to the user to make a program or an
application error and exception free.

Download this example

Now lets see the two different ways to generate an Exception.

1. Exceptions generated by the Java run-time system - These are the exceptions which violate the
rules of the Java language and are related to some fundamental errors.
2. Manually generated Exceptions - These are the exceptions which are being generated manually
by your code and by which some of the error conditions are reported to the caller of a method .
3. As we have seen that java provides a method getMessage() method that is used with
an object of the Exception class to print errors to debug the process. For example:

4.How to Print a Stack Trace Message


5. As we have seen that java provides a method getMessage() method that is used with an
object of the Exception class to print errors to debug the process. For example:

try {
// ......
}
catch (IOException e) {
// ...........
System.out.println("Got an IOException: "
+ e.getMessage());
}

6. Instead of this this method you can get more information about the error process if you
print a stack trace from the exception using the printStackTrace() method that is the
method of the Throwable class and prints the stack trace to the console and provides the
line numbers of statements that called the methods in the current stack.
7. Lets see an example that prints an exception's message.

public class PrintStack{


public static void main (String args[]){
String str = "Exception" ;
int len=0;
try{
StringBuffer sbuf = new StringBuffer(str);
len = str.length() ;
for(int ct=len;ct>=0;ct--){
System.out.print(sbuf.charAt(ct));
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

9. Output of the program:

C:\Roseindia\>javac PrintStack.java

C:\Roseindia\>java PrintStack

java.lang.StringIndexOutOfBoundsException:
String index out of range: 9
at java.lang.StringBuffer.charAt(Unknown
Source)
at PrintStack.main(PrintStack.java:13)

Multithreading in Java:

Processes and Threads


In concurrent programming, there are two basic units of execution: processes and threads. In the
Java programming language, concurrent programming is mostly concerned with threads.
However, processes are also important.

A computer system normally has many active processes and threads. This is true even in systems
that only have a single execution core, and thus only have one thread actually executing at any
given moment. Processing time for a single core is shared among processes and threads through
an OS feature called time slicing.

It's becoming more and more common for computer systems to have multiple processors or
processors with multiple execution cores. This greatly enhances a system's capacity for
concurrent execution of processes and threads — but concurrency is possible even on simple
systems, without multiple processors or execution cores.
Processes

A process has a self-contained execution environment. A process generally has a complete,


private set of basic run-time resources; in particular, each process has its own memory space.

Processes are often seen as synonymous with programs or applications. However, what the user
sees as a single application may in fact be a set of cooperating processes. To facilitate
communication between processes, most operating systems support Inter Process
Communication (IPC) resources, such as pipes and sockets. IPC is used not just for
communication between processes on the same system, but processes on different systems.

Most implementations of the Java virtual machine run as a single process. A Java application can
create additional processes using a ProcessBuilder object. Multiprocess applications are
beyond the scope of this lesson.

Threads
Threads are sometimes called lightweight processes. Both processes and threads provide an
execution environment, but creating a new thread requires fewer resources than creating a new
process.

Threads exist within a process — every process has at least one. Threads share the process's
resources, including memory and open files. This makes for efficient, but potentially
problematic, communication.

Multithreaded execution is an essential feature of the Java platform. Every application has at
least one thread — or several, if you count "system" threads that do things like memory
management and signal handling. But from the application programmer's point of view, you start
with just one thread, called the main thread. This thread has the ability to create additional
threads, as we'll demonstrate in the next section.

Introduction
So far you have learned about a single thread. Lets us know about the concept of multithreading
and learn the implementation of it. But before that, lets be aware from the multitasking.

Multitasking :

Multitasking allow to execute more than one tasks at the same time, a task being a program. In
multitasking only one CPU is involved but it can switches from one program to another program
so quickly that's why it gives the appearance of executing all of the programs at the same time.
Multitasking allow processes (i.e. programs) to run concurrently on the program. For Example
running the spreadsheet program and you are working with word processor also.
Multitasking is running heavyweight processes by a single OS.

Multithreading :

Multithreading is a technique that allows a program or a process to execute many tasks


concurrently (at the same time and parallel). It allows a process to run its tasks in parallel mode
on a single processor system

In the multithreading concept, several multiple lightweight processes are run in a single
process/task or program by a single processor. For Example, When you use a word processor
you perform a many different tasks such as printing, spell checking and so on. Multithreaded
software treats each process as a separate program.

In Java, the Java Virtual Machine (JVM) allows an application to have multiple threads of
execution running concurrently. It allows a program to be more responsible to the user. When a
program contains multiple threads then the CPU can switch between the two threads to execute
them at the same time.
For example, look at the diagram shown as:

In this diagram, two threads are being executed having more than one task. The task of each
thread is switched to the task of another thread.

Advantages of multithreading over multitasking :

 Reduces the computation time.


 Improves performance of an application.
 Threads share the same address space so it saves the memory.
 Context switching between threads is usually less expensive than between processes.
 Cost of communication between threads is relatively low.

Different states implementing Multiple-Threads are:


As we have seen different states that may be occur with the single thread. A running thread can
enter to any non-runnable state, depending on the circumstances. A thread cannot enters directly
to the running state from non-runnable state, firstly it goes to runnable state. Now lets understand
the some non-runnable states which may be occur handling the multithreads.

 Sleeping ? On this state, the thread is still alive but it is not runnable, it might be return to
runnable state later, if a particular event occurs. On this state a thread sleeps for a
specified amount of time. You can use the method sleep( ) to stop the running state of a
thread.

static void sleep(long millisecond) throws InterruptedException


 Waiting for Notification ? A thread waits for notification from another thread. The
thread sends back to runnable state after sending notification from another thread.

final void wait(long timeout) throws InterruptedException


final void wait(long timeout, int nanos) throws InterruptedException
final void wait() throws InterruptedException

 Blocked on I/O ? The thread waits for completion of blocking operation. A thread can
enter on this state because of waiting I/O resource. In that case the thread sends back to
runnable state after availability of resources.

 Blocked for joint completion ? The thread can come on this state because of waiting the
completion of another thread.

 Blocked for lock acquisition ? The thread can come on this state because of waiting to
acquire the lock of an object.

Java provides built-in support for multithreaded programming. A multithreaded program


contains two or more parts that can run concurrently. Each part of such a program is called a
thread, and each thread defines a separate path of execution.
A multithreading is a specialized form of multitasking. Multitasking threads require less
overhead than multitasking processes.

I need to define another term related to threads: process: A process consists of the memory space
allocated by the operating system that can contain one or more threads. A thread cannot exist on
its own; it must be a part of a process. A process remains running until all of the non-daemon
threads are done executing.

Multithreading enables you to write very efficient programs that make maximum use of the
CPThread Objects

Each thread is associated with an instance of the class Thread. There are two basic strategies for
using Thread objects to create a concurrent application.

 To directly control thread creation and management, simply instantiate Thread each time the
application needs to initiate an asynchronous task.
 To abstract thread management from the rest of your application, pass the application's tasks to
an executor.

This section documents the use of Thread objects. Executors are discussed with other high-level
concurrency objects.

U, because idle time can be kept to a minimum.

Life Cycle of a Thread:


A thread goes through various stages in its life cycle. For example, a thread is born, started, runs,
and then dies. Following diagram shows complete life cycle of a thread.
Above mentioned stages are explained here:

 New: A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
 Runnable: After a newly born thread is started, the thread becomes runnable. A thread in
this state is considered to be executing its task.
 Waiting: Sometimes a thread transitions to the waiting state while the thread waits for
another thread to perform a task.A thread transitions back to the runnable state only when
another thread signals the waiting thread to continue executing.
 Timed waiting: A runnable thread can enter the timed waiting state for a specified
interval of time. A thread in this state transitions back to the runnable state when that
time interval expires or when the event it is waiting for occurs.
 Terminated: A runnable thread enters the terminated state when it completes its task or
otherwise terminates.

Thread Priorities:
Every Java thread has a priority that helps the operating system determine the order in which
threads are scheduled.

Java priorities are in the range between MIN_PRIORITY (a constant of 1) and


MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated processor
time before lower-priority threads. However, thread priorities cannot guarantee the order in
which threads execute and very much platform dependentant.

Creating a Thread:
Java defines two ways in which this can be accomplished:

 You can implement the Runnable interface.


 You can extend the Thread class, itself.

Create Thread by Implementing Runnable:

The easiest way to create a thread is to create a class that implements the Runnable interface.

To implement Runnable, a class need only implement a single method called run( ), which is
declared like this:

public void run( )

You will define the code that constitutes the new thread inside run() method. It is important to
understand that run() can call other methods, use other classes, and declare variables, just like the
main thread can.

After you create a class that implements Runnable, you will instantiate an object of type Thread
from within that class. Thread defines several constructors. The one that we will use is shown
here:

Thread(Runnable threadOb, String threadName);

Here threadOb is an instance of a class that implements the Runnable interface and the name of
the new thread is specified by threadName.

After the new thread is created, it will not start running until you call its start( ) method, which
is declared within Thread. The start( ) method is shown here:

void start( );

Example:

Here is an example that creates a new thread and starts it running:


// Create a new thread.
class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}

// This is the entry point for the second thread.


public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
// Let the thread sleep for a while.
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}

class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}

This would produce following result:

Child thread: Thread[Demo Thread,5,main]


Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.

Create Thread by Extending Thread:

The second way to create a thread is to create a new class that extends Thread, and then to
create an instance of that class.

The extending class must override the run( ) method, which is the entry point for the new thread.
It must also call start( ) to begin execution of the new thread.

Example:

Here is the preceding program rewritten to extend Thread:

// Create a second thread by extending Thread


class NewThread extends Thread {
NewThread() {
// Create a new, second thread
super("Demo Thread");
System.out.println("Child thread: " + this);
start(); // Start the thread
}

// This is the entry point for the second thread.


public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
// Let the thread sleep for a while.
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}

class ExtendThread {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}

This would produce following result:

Child thread: Thread[Demo Thread,5,main]


Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.

Thread Methods:
Following is the list of important medthods available in the Thread class.

SN Methods with Description

public void start()


1 Starts the thread in a separate path of execution, then invokes the run() method on this Thread
object.

public void run()


2 If this Thread object was instantiated using a separate Runnable target, the run() method is
invoked on that Runnable object.

public final void setName(String name)


3
Changes the name of the Thread object. There is also a getName() method for retrieving the name.

public final void setPriority(int priority)


4
Sets the priority of this Thread object. The possible values are between 1 and 10.

public final void setDaemon(boolean on)


5
A parameter of true denotes this Thread as a daemon thread.
public final void join(long millisec)
6 The current thread invokes this method on a second thread, causing the current thread to block
until the second thread terminates or the specified number of milliseconds passes.

public void interrupt()


7
Interrupts this thread, causing it to continue execution if it was blocked for any reason.

public final boolean isAlive()


8 Returns true if the thread is alive, which is any time after the thread has been started but before it
runs to completion.

The previous methods are invoked on a particular Thread object. The following methods in the
Thread class are static. Invoking one of the static methods performs the operation on the
currently running thread

SN Methods with Description

public static void yield()


1 Causes the currently running thread to yield to any other threads of the same priority that are
waiting to be scheduled

public static void sleep(long millisec)


2
Causes the currently running thread to block for at least the specified number of milliseconds

public static boolean holdsLock(Object x)


3
Returns true if the current thread holds the lock on the given Object.

public static Thread currentThread()


4
Returns a reference to the currently running thread, which is the thread that invokes this method.

public static void dumpStack()


5 Prints the stack trace for the currently running thread, which is useful when debugging a
multithreaded application.

Example:

The following ThreadClassDemo program demonstrates some of these methods of the Thread
class:
// File Name : DisplayMessage.java
// Create a thread to implement Runnable
public class DisplayMessage implements Runnable
{
private String message;
public DisplayMessage(String message)
{
this.message = message;
}
public void run()
{
while(true)
{
System.out.println(message);
}
}
}

// File Name : GuessANumber.java


// Create a thread to extentd Thread
public class GuessANumber extends Thread
{
private int number;
public GuessANumber(int number)
{
this.number = number;
}
public void run()
{
int counter = 0;
int guess = 0;
do
{
guess = (int) (Math.random() * 100 + 1);
System.out.println(this.getName()
+ " guesses " + guess);
counter++;
}while(guess != number);
System.out.println("** Correct! " + this.getName()
+ " in " + counter + " guesses.**");
}
}

// File Name : ThreadClassDemo.java


public class ThreadClassDemo
{
public static void main(String [] args)
{
Runnable hello = new DisplayMessage("Hello");
Thread thread1 = new Thread(hello);
thread1.setDaemon(true);
thread1.setName("hello");
System.out.println("Starting hello thread...");
thread1.start();
Runnable bye = new DisplayMessage("Goodbye");
Thread thread2 = new Thread(hello);
thread2.setPriority(Thread.MIN_PRIORITY);
thread2.setDaemon(true);
System.out.println("Starting goodbye thread...");
thread2.start();

System.out.println("Starting thread3...");
Thread thread3 = new GuessANumber(27);
thread3.start();
try
{
thread3.join();
}catch(InterruptedException e)
{
System.out.println("Thread interrupted.");
}
System.out.println("Starting thread4...");
Thread thread4 = new GuessANumber(75);

thread4.start();
System.out.println("main() is ending...");
}
}

This would produce following result. You can try this example again and again and you would
get different result every time.

Starting hello thread...


Starting goodbye thread...
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Thread-2 guesses 27
Hello
** Correct! Thread-2 in 102 guesses.**
Hello
Starting thread4...
Hello
Hello
..........remaining result produced.

Concurrency
Computer users take it for granted that their systems can do more than one thing at a time. They
assume that they can continue to work in a word processor, while other applications download
files, manage the print queue, and stream audio. Even a single application is often expected to do
more than one thing at a time. For example, that streaming audio application must
simultaneously read the digital audio off the network, decompress it, manage playback, and
update its display. Even the word processor should always be ready to respond to keyboard and
mouse events, no matter how busy it is reformatting text or updating the display. Software that
can do such things is known as concurrent software.

The Java platform is designed from the ground up to support concurrent programming, with
basic concurrency support in the Java programming language and the Java class libraries. Since
version 5.0, the Java platform has also included high-level concurrency APIs. This lesson
introduces the platform's basic concurrency support and summarizes some of the high-level APIs
in the java.util.concurrent packages.

Interrupts
An interrupt is an indication to a thread that it should stop what it is doing and do something
else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is
very common for the thread to terminate. This is the usage emphasized in this lesson.

A thread sends an interrupt by invoking interrupt on the Thread object for the thread to be
interrupted. For the interrupt mechanism to work correctly, the interrupted thread must support
its own interruption.

Supporting Interruption

How does a thread support its own interruption? This depends on what it's currently doing. If the
thread is frequently invoking methods that throw InterruptedException, it simply returns
from the run method after it catches that exception. For example, suppose the central message
loop in the SleepMessages example were in the run method of a thread's Runnable object. Then
it might be modified as follows to support interrupts:

for (int i = 0; i < importantInfo.length; i++) {


// Pause for 4 seconds
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
// We've been interrupted: no more messages.
return;
}
// Print a message
System.out.println(importantInfo[i]);
}

Many methods that throw InterruptedException, such as sleep, are designed to cancel their
current operation and return immediately when an interrupt is received.
What if a thread goes a long time without invoking a method that throws
InterruptedException? Then it must periodically invoke Thread.interrupted, which returns
true if an interrupt has been received. For example:

for (int i = 0; i < inputs.length; i++) {


heavyCrunch(inputs[i]);
if (Thread.interrupted()) {
// We've been interrupted: no more crunching.
return;
}
}

In this simple example, the code simply tests for the interrupt and exits the thread if one has been
received. In more complex applications, it might make more sense to throw an
InterruptedException:

if (Thread.interrupted()) {
throw new InterruptedException();
}

This allows interrupt handling code to be centralized in a catch clause.

The Interrupt Status Flag

The interrupt mechanism is implemented using an internal flag known as the interrupt status.
Invoking Thread.interrupt sets this flag. When a thread checks for an interrupt by invoking
the static method Thread.interrupted, interrupt status is cleared. The non-static
isInterrupted method, which is used by one thread to query the interrupt status of another,
does not change the interrupt status flag.

By convention, any method that exits by throwing an InterruptedException clears interrupt


status when it does so. However, it's always possible that interrupt status will immediately be set
again, by another thread invoking interrupt.

Joins
The join method allows one thread to wait for the completion of another. If t is a Thread object
whose thread is currently executing,

t.join();

causes the current thread to pause execution until t's thread terminates. Overloads of join allow
the programmer to specify a waiting period. However, as with sleep, join is dependent on the
OS for timing, so you should not assume that join will wait exactly as long as you specify.

Like sleep, join responds to an interrupt by exiting with an InterruptedException.


2.3. Volatile
If a variable is declared as volatile then is guaranteed that any thread which reads the field will
see the most recently written value. The keyword volatile will not perform any mutual exclusive
lock on the variable.

As of Java 5 write access to a volatile variable will also update non-volatile variables which were
modified by the same thread. This can also be used to update values within a reference variable,
e.g. for a volatile variable person. In this case you must use a temporary variable person and use
the setter to initialize the variable and then assign the temporary variable to the final variable.
This will then make the address changes of this variable and the values visible to other threads.

. The Java memory model


3.1. Overview

The Java memory model describes the communication between the memory of the threads and
the main memory, e.g. then are changes of threads visible to others and then does a thread re-
fresh its own memory from the main memory.

It also describes which operations are atomic and the ordering of operations.

3.2. Atomic operation

An atomic operation is an operation which is performed as a single unit of work without the
possibility of interference from other operations.

In Java the language specification guarantees that that reading or writing a variable is atomic
(unless the variable is of type long or double). Long and double are only atomic if they declared
as volatile.

The operation i++ it not atomic in Java for the standard variables (int, long, etc). It first reads the
value which is currently stored in i (atomic operations) and then it adds one to it (atomic
operation). But between the read and the write the value of i might have changed. Java

Since Java 1.5 the java language provides atomic variables, e.g. AtomicInteger or AtomicLong
which provide methods like getAndDecrement(), getAndIncrement() and getAndSet() which are
atomic.

3.3. The "synchronized" keyword

For variables which are protected by synchronized it it guaranteed by the Java memory model
that each thread entering a synchronized block of code sees the effects of all previous
modifications that were guarded by the same lock.
3.4. The "volatile" keyword

If a variable is declared as volatile then is guaranteed that any thread which reads the field will
see the most recently written value.

4. Immutability and Defensive Copies


4.1. Immutability

The simplest way to avoid problems with concurrency is to share only immutable data between
threads. Immutable data is data which can not changed.

To make a class immutable make

 all its fields final


 the class declared as final
 the this reference is not allowed to escape during construction
 Any fields which refer to mutable data objects are
o private
o have no setter method
o they are never directly returned of otherwise exposed to a caller
o if they are changed internally in the class this change is not visible and has no
effect outside of the class

An immutable class may have some mutable data which is uses to manages its state but from the
outside this class nor any attribute of this classes can get changed.

For all mutable fields, e.g. Arrays, that are passed from the outside to the class during the
construction phase, the class needs to make a defensive-copy of the elements to make sure that
no other object from the outside still can change the data

4.2. Defensive Copies

You must protected your classes from calling code. Assume that calling code will do its best to
change your data in a way you didn't expect it. While this is especially true in case of immutable
data it is also true for non-immutable data which you still not expect that this data is changed
outside your class.

To protect your class against that you should copy data you receive and only return copies of
data to calling code.

The following example creates a copy of a list (ArrayList) and returns only the copy of the list.
This way the client of this class cannot remove elements from the list.

package de.vogella.performance.defensivecopy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MyDataStructure {


List<String> list = new ArrayList<String>();

public void add(String s) {


list.add(s);
}

/**
* Makes a defensive copy of the List and return it
* This way cannot modify the list itself
*
* @return List<String>
*/

public List<String> getList() {


return Collections.unmodifiableList(list);
}
}

Collections FrameWork:

collection is simply an object that groups multiple elements into a single unit. It is also
called as a container sometimes.

Introduction to Collections API


As the name indicates, collections are a group of objects known as its elements. Basically it is
a package of data structures that includes ArrayLists, LinkedLists, HashSets, etc. A collection
is simply an object that groups multiple elements into a single unit. It is also called as a container
sometimes. It is used to store, retrieve, manipulate, and communicate aggregate data. Typically,
it represents data items that form a natural group and allows duplicate elements while others do
not. It consists of both ordered and unordered elements. There is no direct implementation of this
interface however SDK provides implementations of more specific sub interfaces like Set and
List. The manipulation and passing of collections is done by this interface.

The Two "standard" constructors should be provided by all the general-purpose Collection
implementation classes. These classes typically implement Collection indirectly through one of
its sub interfaces.

1. Void (no arguments) constructor which creates an empty collection.


2. Constructor with a single argument of type Collection, which creates a new collection
with the same elements as its argument.

The user can copy any collection using void constructor to produce an equivalent collection of
the desired implementation type. As interfaces cannot contain constructors there is no way to
enforce this convention. However all of the general-purpose Collection implementations comply
this in the Java platform libraries.

The Java Collections API:

Java Collections of API (Application Programming Intreface) Consists of several interfaces, and
classes that implement those interfaces, within the java.util package. It provides tools for
maintaining a data container of objects. Each primitive value must be wrapped in an object of its
appropriate wrapper class (Boolean, Character, Integer, Double, etc.) to maintain a collection
of primitive data. It is an alternative tool to the creation of custom data structures.

You must be familiar with collections if you have worked with Java programming language .
Collection implementations included Vector, Hashtable, and array are available in earlier (pre-
1.2) versions of the Java platform, but those versions do not include the collections framework.
Hence the new version of the Java platform contains the collections framework.

Collections Framework
Interfaces
The core collection interfaces encapsulate different types of collections, which are shown in the
figure below. These interfaces allow collections to be manipulated independently of the details of
their representation. Core collection interfaces are the foundation of the Java Collections
Framework. As you can see in the following figure, the core collection interfaces form a
hierarchy.

The core collection interfaces.

A Set is a special kind of Collection, a SortedSet is a special kind of Set, and so forth. Note
also that the hierarchy consists of two distinct trees — a Map is not a true Collection.
Note that all the core collection interfaces are generic. For example, this is the declaration of the
Collection interface.

public interface Collection<E>...

The <E> syntax tells you that the interface is generic. When you declare a Collection instance
you can and should specify the type of object contained in the collection. Specifying the type
allows the compiler to verify (at compile-time) that the type of object you put into the collection
is correct, thus reducing errors at runtime. For information on generic types, see the Generics
lesson.

When you understand how to use these interfaces, you will know most of what there is to know
about the Java Collections Framework. This chapter discusses general guidelines for effective
use of the interfaces, including when to use which interface. You'll also learn programming
idioms for each interface to help you get the most out of it.

To keep the number of core collection interfaces manageable, the Java platform doesn't provide
separate interfaces for each variant of each collection type. (Such variants might include
immutable, fixed-size, and append-only.) Instead, the modification operations in each interface
are designated optional — a given implementation may elect not to support all operations. If an
unsupported operation is invoked, a collection throws an UnsupportedOperationException.
Implementations are responsible for documenting which of the optional operations they support.
All of the Java platform's general-purpose implementations support all of the optional operations.

The following list describes the core collection interfaces:

 Collection — the root of the collection hierarchy. A collection represents a group of objects
known as its elements. The Collection interface is the least common denominator that all
collections implement and is used to pass collections around and to manipulate them when
maximum generality is desired. Some types of collections allow duplicate elements, and others
do not. Some are ordered and others are unordered. The Java platform doesn't provide any
direct implementations of this interface but provides implementations of more specific
subinterfaces, such as Set and List. Also see The Collection Interface section.
 Set — a collection that cannot contain duplicate elements. This interface models the
mathematical set abstraction and is used to represent sets, such as the cards comprising a poker
hand, the courses making up a student's schedule, or the processes running on a machine. See
also The Set Interface section.
 List — an ordered collection (sometimes called a sequence). Lists can contain duplicate
elements. The user of a List generally has precise control over where in the list each element is
inserted and can access elements by their integer index (position). If you've used Vector,
you're familiar with the general flavor of List. Also see The List Interface section.
 Queue — a collection used to hold multiple elements prior to processing. Besides basic
Collection operations, a Queue provides additional insertion, extraction, and inspection
operations.

Queues typically, but do not necessarily, order elements in a FIFO (first-in, first-out)
manner. Among the exceptions are priority queues, which order elements according to a
supplied comparator or the elements' natural ordering. Whatever the ordering used, the
head of the queue is the element that would be removed by a call to remove or poll. In a
FIFO queue, all new elements are inserted at the tail of the queue. Other kinds of queues
may use different placement rules. Every Queue implementation must specify its ordering
properties. Also see The Queue Interface section.

 Map — an object that maps keys to values. A Map cannot contain duplicate keys; each key can
map to at most one value. If you've used Hashtable, you're already familiar with the basics of
Map. Also see The Map Interface section.

The last two core collection interfaces are merely sorted versions of Set and Map:

 SortedSet — a Set that maintains its elements in ascending order. Several additional
operations are provided to take advantage of the ordering. Sorted sets are used for naturally
ordered sets, such as word lists and membership rolls. Also see The SortedSet Interface section.
 SortedMap — a Map that maintains its mappings in ascending key order. This is the Map analog
of SortedSet. Sorted maps are used for naturally ordered collections of key/value pairs, such
as dictionaries and telephone directories. Also see The SortedMap Interface section.

To understand how the sorted interfaces maintain the order of their elements, see the Object
Ordering section.

Java provides the Collections Framework. In the Collection Framework, a collection represents
the group of the objects. And a collection framework is the unified architecture that represent and
manipulate collections. The collection framework provides a standard common programming
interface to many of the most common abstraction without burdening the programmer with many
procedures and interfaces. It provides a system for organizing and handling collections. This
framework is based on:

 Interfaces that categorize common collection types.


 Classes which proves implementations of the Interfaces.
 Algorithms which proves data and behaviors need when using collections i.e. search, sort,
iterate etc.

Following is the hierarchical representation for the relationship of all four interfaces of the
collection framework which illustrates the whole implementation of the framework.
During the designing of a software (application) it need to be remember the following
relationship of the four basic interfaces of the framework are as follows:

 The Collection interface which is the collection of objects. That permits the duplication of the
value or objects.
 Set is the interface of the collections framework which extends the Collection but forbids
duplicates.
 An another interface is the List which also extends the Collection. It allows the duplicates objects
on different position because it introduces the positional indexing.
 And Map is also a interface of the collection framework which extends neither Set nor
Collection.

Some interfaces and classes of the collection framework are as follows:

INTERFACES CLASSES

Collection Interface HashSet Class


Iterator Interface TreeSet Class
Set Interface ArrayList Class
List Interface LinkedList Class
ListIterator Interface HashMap Class
Map Interface TreeMap Class
SortedSet Interface Vector Class
SortedMap Interface Stack Class

Every interfaces and classes are explained next in the roseidia.net java tutorial one by one in the
various examples.
Advantages and Disadvantages of the Collection Framework
In this section, you will learn the advantages and disadvantages of Java Collection Framework. A
collection is simply an object that groups multiple elements into a single unit. It is also called as
a container sometimes. It is used to store, retrieve, manipulate, and communicate aggregate data.
Typically, it represents data items that form a natural group and allows duplicate elements while
others do not. It consists of both ordered and unordered elements.

Advantages of collections framework:

The collections framework offers developers the following benefits:

Benefits of the Java Collections Framework

The Java Collections Framework provides the following benefits:

 Reduces programming effort: By providing useful data structures and algorithms, the
Collections Framework frees you to concentrate on the important parts of your program rather
than on the low-level "plumbing" required to make it work. By facilitating interoperability
among unrelated APIs, the Java Collections Framework frees you from writing adapter objects or
conversion code to connect APIs.
 Increases program speed and quality: This Collections Framework provides high-performance,
high-quality implementations of useful data structures and algorithms. The various
implementations of each interface are interchangeable, so programs can be easily tuned by
switching collection implementations. Because you're freed from the drudgery of writing your
own data structures, you'll have more time to devote to improving programs' quality and
performance.
 Allows interoperability among unrelated APIs: The collection interfaces are the vernacular by
which APIs pass collections back and forth. If my network administration API furnishes a
collection of node names and if your GUI toolkit expects a collection of column headings, our
APIs will interoperate seamlessly, even though they were written independently.
 Reduces effort to learn and to use new APIs: Many APIs naturally take collections on input and
furnish them as output. In the past, each such API had a small sub-API devoted to manipulating
its collections. There was little consistency among these ad hoc collections sub-APIs, so you had
to learn each one from scratch, and it was easy to make mistakes when using them. With the
advent of standard collection interfaces, the problem went away.
 Reduces effort to design new APIs: This is the flip side of the previous advantage. Designers and
implementers don't have to reinvent the wheel each time they create an API that relies on
collections; instead, they can use standard collection interfaces.
 Fosters software reuse: New data structures that conform to the standard collection interfaces
are by nature reusable. The same goes for new algorithms that operate on objects that
implement these interfaces.
 It increases the readability of your collections by providing a standard set of interfaces which
has to be used by many programmers in different applications.
 It makes your code more flexible. You can make the code flexible by using many interfaces and
classes of the collection framework.
 It offers many specific implementations of the interfaces. It allows you to choose the collection
that is most fitting and which offers the highest performance for your purposes.

Interfaces of the collections framework are very easy to use. These interfaces can be
transparently substituted to increase the developed application performance.

We need not to learn multiple ad hoc collection APIs.

1. It provides a standard interface for collections that fosters software reuse and also
provides algorithms to manipulate them.
2. Reduces the effort required to design and implement APIs by eliminating the need to
produce ad hoc collections APIs.
3. It provides useful data structures and algorithms that reduces programming effort due to
which we need not to write them ourselves.
4. It provides high-performance implementations of useful data structures and algorithms
that increases the performance.
5. Helps in establishing a common language to pass collections back and forth that provides
interoperability between unrelated APIs.
6. Collection is resizable and can grow.

Disadvantages of collections framework:

1. It must cast to correct type.


2. It can't be done compile-time type checking.

Java 6.0 Collection Framework

Some of the new collections APIs have been introduced in Java 6.0. These are:

1. Deque: It is used to represent Double ended queue. With the help of this collection we
can add or remove elements at both the ends. Deque implementation can be used as Stack
(Last in first out) or Queue (First in First Out). There are two methods in Deque,
which are used for insertion, retrieval and removal of elements. One returns status or
special value for each operation and the other will throw exception if it fails in an
operation.

2. BlockingDeque: It is similar to Deque but with added functionality. When we try to


insert an element in a BlockingDeque and if the BlockingDeque is already full then the
element can wait till the space becomes available to insert an element. There are four
methods available for BlockingDeque.
 Methods throws exception
 Methods that times out (Waits for a given time for space to available)
 Methods that blocks (Waits indefinitely for space to available)
 Methods returns special value

3. NavigableSet: It is used to return the closest matches of elements. For instance if we


want retrieve the element, which is immediately greater than, or lower than element 20 or
if we want to retrieve all elements greater than or lower than 35 from sorted set elements
[10,20,35,5] we can use NavigableSet methods that becomes just a method call.
ConcurrentSkipListSet is one of the class that implements NavigableSet.

4. NavigableMap: In NavigableSet, methods use to return values, but in NaviagableMap


methods used to return the key,value pair. ConcurrentSkipListMap is the one of the
class which implements NaviagableMap

Some of the new Classes are:

1. ArrayDeque: ArrayDeque is a class that implements Deque. If used as a stack or linked


list, it performs much faster than before. It is neither thread safe nor has capacity
restrictions.

2. LinkedBlockingDeque: It implements BlockingDeque. Maximum capacity can be


specified by using BlockingDeque interface. However the maximum capacity will be
Integer.MAX_VALUE if not specified.

3. ConcurrentSkipListSet: ConcurrentSkipListSet is one of the class that implements


NavigableSet. It is used to return the closest matches of elements.

4. ConcurrentSkipListMap: ConcurrentSkipListMap is the one of the class which


implements NaviagableMap. In NavigableSet, methods use to return values.

5. AbstractMap.SimpleEntry: The key value pair of one single entry in a Map is held by
the instance of this class. Moreover it is a static nested class nested inside abstractMap
class.

6. AbstractMap.SimpleImmutableEntry: This class is similar to


AbstractMap.SimpleEntry class however it has one difference that it throws the
exception UnsupportedOperationException when we try to set a value while
AbstractMap.SimpleEntry doesn?t.

Updated Classes in Java 6.0

1. LinkedList

2. TreeSet
3. TreeMap

4. Collections

Modified classes

To implement the new interfaces we modify some classes like TreeSet is modified to implement
NavigableSet, LinkedList is modified to implement Deque, TreeMap is modified to implement
NavigableMap etc. Some of the new methods like newSetFromMap and asLifoQueue have
been added to Collections 2.

Hence the bi- directional traversal has become easier with java6.0 collections. We can even
retrieve elements as desired.

Collections Framework Enhancements

In Collection framework, we are able to improve the performance hashing function that is used
by java.util.HashMap. It provides some new Collection interfaces also.

Following new Interfaces and Classes are provided in JAVA SE 6 :

 Deque ? Deque is a interface. It is a short for ?Double Ended Queue?. This interface
defines some methods that access the element at both ends. That means by the methods of
this interface we can add and remove the elements at both ends.
 ArrayDeque ? ArrayDeque Class implements a Deque interface. This class have no
capacity restriction, it can grow according to usage. If the external Synchronization is not
available then it don?t support concurrent access by multiple thread.

Constructors Details :

 public ArrayDeque()
Above Constructor is used to make a empty array deque with an default capacity that 16
elements.
 public ArrayDeque(int numElements)
Above Construtor is used to make a empty array deque with the initial capacity that is
sufficient to hold the specified elements.
 public ArrayDeque<Etype>()
Etype is the type of the elements that held in this Collection. Above Constructor is used
to make a array deque containing elements of specified type.

Methods Details :
 void addFirst(Etype e)
Above method is used to insert the element at the starting point of the array deque
 void addLast(Etype e)
Above method is used to insert the element at the end point of the array deque.

Above two methods throws following Exception:

i. IllegalStateException ? Due to capacity restriction the element cannot be added.


ii. ClassCastException ? Class of the specified element prevents it from being added to this
deque
iii. NullPointerException ? If specified element is null.
iv. IllegalArgumentException ? If element having some property that prevent it from being
added to this deque

 boolean offerFirst(Etype e)
Above method is also used to insert the specified element at the starting point of the array
deque. This method is preferable when we using a capacity restricted deque. When
element is added in array deque then its return true else it return false.
 boolean offerLast(Etype e)
Above method is also used to insert the specified element at the end point of the array
deque. This method is preferable when we using a capacity restricted deque. When
element is added in array deque then its return true else it return false.

Above two methods throws following Exception:

i. ClassCastException ? Class of the specified element prevents it from being added to this
deque.
ii. NullPointerException ? If specified element is null.
iii. IllegalArgumentException ? If element having some property that prevent it from being
added to this deque.

 Etype removeFirst()
Above method is used to remove the first element of the array deque. And we can also
retrieve this element. But if array deque is empty then it throws a
NoSuchElementException.
 Etype removeLast()
Above method is used to remove the last element of the array deque. And we can also
retrieve this element. But if array deque is empty then it throws a
NoSuchElementException.
 Etype pollFirst()
Above method is same as removeFirst(). It is also used to retrieve and remove the first
element of the deque. But it does not throws any Exception even the deque is empty, its
only return null.
 Etype pollLast()
Above method is same as removeLast(). It is also used to retrieve and remove the last
element of the deque. But it does not throws any Exception even the deque is empty, its
only return null.
 Etype getFirst()
Above method is used just for retrieving the first element of deque. But if array deque is
empty then it throws a NoSuchElementException.
 Etype getLast()
Above method is used just for retrieving the last element of deque. But if array deque is
empty then it throws a NoSuchElementException.
 Etype peekFirst()
Above method is same as getFirst().It is also used to retrieving the first element of the
deque. But it does not throws any Exception even the deque is empty, its only return null.
 Etype peekLast()
Above method is same as getLast().It is also used to retrieving the last element of the
deque. But it does not throws any Exception even the deque is empty, its only return null.
 boolean removeFirstOccurrence(Object obj)
Above method is used to remove the first occurrence of the specified element. It return
true when the specified element was remove. But if the deque does not contain the
specified element it is unchanged.
 boolean removeLastOccurrence(Object obj)
Above method is used to remove the last occurrence of the specified element. It return
true when the specified element was remove. But if the deque does not contain the
specified element it is unchanged.

Navigable Map Example

We already know that NavigableMap is similar to NavigableSet. In NavigableMap we use methods to


return the key value pair like navMap.put(1, "January"); whereas in NavigableSet we use methods to
return values. ConcurrentSkipListMap is the one of the class which implements NavigableMap. Lets
have a look at the example.

Description of program:

The following program helps you in inserting, removing and retrieving the data from the
NavigableMap. It uses the put() method to add the element. If you want to retrieve the data at
first and last position from the NavigableMap, you use the firstEntry() and lastEntry()
methods. The descendingMap() method represents all data to the NavigableMap in descending
order.

You can retrieve the nearest less than or equal to the given number and the greatest key strictly
less than the given number floorEntry() and lowerEntry() methods. And you retrieve a key-
value associated with the least key strictly greater than the given key, you use the higherEntry()
method. The pollFirstEntry() method removes the first data from the NavigableMap and
pollLastEntry() method also removes the data at the last position from the NavigableMap.
Here is the code of program:

import java.util.*;
import java.util.concurrent.*;

public class NavigableMapExample{


public static void main(String[] args) {
System.out.println("Navigable Map Example!\n");
NavigableMap <Integer, String>navMap = new
ConcurrentSkipListMap<Integer, String>();
navMap.put(1, "January");
navMap.put(2, "February");
navMap.put(3, "March");
navMap.put(4, "April");
navMap.put(5, "May");
navMap.put(6, "June");
navMap.put(7, "July");
navMap.put(8, "August");
navMap.put(9, "September");
navMap.put(10, "October");
navMap.put(11, "November");
navMap.put(12, "December");
//Displaying all data
System.out.println("Data in the navigable map: " +
navMap.descendingMap()+"\n");
//Retrieving first data
System.out.print("First data: " + navMap.firstEntry()+"\n");
//Retrieving last data
System.out.print("Last data: " + navMap.lastEntry()+"\n\n");
//Retrieving the nreatest less than or equal to the given key
System.out.print("Nearest less than or equal to the given key: "
+ navMap.floorEntry(5)+"\n");
//Retrieving the greatest key strictly less than the given key
System.out.println("Retrieving the greatest key strictly less than
the given key: " + navMap.lowerEntry(3));
//Retrieving a key-value associated with the least key
strictly greater than the given key
System.out.println("Retriving data from navigable map greter than
the given key: " + navMap.higherEntry(5)+"\n");
//Removing first
System.out.println("Removing First: " + navMap.pollFirstEntry());
//Removing last
System.out.println("Removing Last: " + navMap.pollLastEntry()+"\n");
//Displaying all data
System.out.println("Now data: " + navMap.descendingMap());
}
}
Download this example.

Output of program:

C:\vinod\collection>javac NavigableMapExample.java

C:\vinod\collection>java NavigableMapExample
Navigable Map Example!

Data in the navigable map: {12=December, 11=November,


10=October, 9=September, 8
=August, 7=July, 6=June, 5=May, 4=April, 3=March,
2=February, 1=January}

First data: 1=January


Last data: 12=December

Nearest less than or equal to the given key: 5=May


Retrieving the greatest key strictly less than the given key:
2=February
Retriving data from navigable map greter than the given key:
6=June

Removing First: 1=January


Removing Last: 12=December

Now data: {11=November, 10=October, 9=September,


8=August, 7=July, 6=June, 5=May
, 4=April, 3=March, 2=February}

Navigable Set Example

In the example below we have used NavigableSet method to sort the elements in ascending
order, descending order, also to retrieve the element which is immediately greater than or equal
to 35 etc. With the help of NavigableSet methods its just a method call to get the result. It is used
to return the closest matches of elements for the given elements in the collection.

Description of program:
Inserting the data in the NavigableSet by the add() method. The NavigableSet provides the
facility to getting the data in both orders: ascending and descending orders. The descendingSet()
method returns the data from the NavigableSet in descending order. If you want to get the data in
ascending order must be used an iterator. An iterator stores the data as a index and the hasNext()
method returns 'true' until, the next() method returns the element in ascending order.

Here, you remove the element from the NavigableSet at first and last position, you use the
pollFirst() and pollLast() methods. Sometimes, you want to get the less and greater than or
equal to the given element by using the floor() and ceiling() methods. For getting the all
elements of the NavigableSet that is greater than or equal to the given element by the tailSet()
method and less than or equal to the given element of the NavigableSet by the headSet()
method.

Here is the code of program:

import java.util.*;
import java.util.concurrent.*;

public class NavigableSetExample{


public static void main(String[] args) {
System.out.println("Navigable set Example!\n");
NavigableSet <Integer>nSet = new ConcurrentSkipListSet<Integer>();
nSet.add(10);
nSet.add(20);
nSet.add(50);
nSet.add(30);
nSet.add(100);
nSet.add(80);
// Returns an iterator over the elements in navigable set,
in ascending order.
Iterator iterator = nSet.iterator();
System.out.print("Ascending order navigable set: ");
//Ascending order list
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();
//Descending order list
System.out.println("Descending order navigable set: " +
nSet.descendingSet() + "\n");
//Greater than or equal to the given element
System.out.println("Least element in Navigable set greater than
or equal to 35: " + nSet.ceiling(35));
//Less than or equal to the given element
System.out.println("Greatest element in Navigable set less than
or equal to 35: " + nSet.floor(35) + "\n");
//Viewing the portion of navigable set whose elements are
strictly less than the given element
System.out.println("Navigable set whose elements are strictly
less than '40': " + nSet.headSet(40));
//Viewing the portion of navigable set whose elements are
greater than or equal to the given element
System.out.println("Navigable set whose elements are greater
than or equal to '40': " + nSet.tailSet(40) + "\n");
//Removing first element from navigable set
System.out.println("Remove element: "+nSet.pollFirst());
//After removing the first element, now get navigable set
System.out.println("Now navigable set: " + nSet.descendingSet() + "\n");
//Removing last element from navigable set
System.out.println("Remove element: " + nSet.pollLast());
//After removing the last element, now get navigable set
System.out.println("Now navigable set: " + nSet.descendingSet());
}
}

Download this Example.

Output of this program

C:\vinod\collection>javac
NavigableSetExample.java

C:\vinod\collection>java NavigableSetExample
Navigable set Example!

Ascending order navigable set: 10 20 30 50 80 100


Descending order navigable set: [100, 80, 50, 30,
20, 10]

Least element in Navigable set greater than or


equal to 35: 50
Greatest element in Navigable set less than or
equal to 35: 30

Navigable set whose elements are strictly less than


'40': [10, 20, 30]
Navigable set whose elements are greater than or
equal to '40': [50, 80, 100]

Remove element: 10
Now navigable set: [100, 80, 50, 30, 20]
Remove element: 100
Now navigable set: [80, 50, 30, 20]

C:\vinod\collection>

HashSet Example

In this section we are discussing HashSet with example code that shows the methods to add,
remove and iterate the values of collection. A HashSet is a collection set that neither allows
duplicate elements nor order or position its elements.

Description of program:

In the following code segment we are performing various operations on HashSet collection. We have
explained the steps to add, remove, and test the elements of the collection. Keys are used to put and
get values. We can also execute this code on a Vector by changing the HashSet declaration and
constructor to a Vector as it supports the collection interface.

To insert an element in the HashSet collection add() method is used. The size() method helps you in
getting the size of the collection. If you want to delete any element, use the remove() method which
takes index as parameter. In order to remove all data from the HashSet use clear() method. When the
HashSet is empty, our program checks for it and displays a message "Collection is empty". If the
collection is not empty then program displays the size of HashSet.

Here is the code of program:

import java.util.*;

public class CollectionTest {


public static void main(String [] args) {
System.out.println( "Collection Example!\n" );
int size;
// Create a collection
HashSet <String>collection = new HashSet <String>();
String str1 = "Yellow", str2 = "White", str3 = "Green", str4 = "Blue";
Iterator iterator;
//Adding data in the collection
collection.add(str1);
collection.add(str2);
collection.add(str3);
collection.add(str4);
System.out.print("Collection data: ");
//Create a iterator
iterator = collection.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();
// Get size of a collection
size = collection.size();
if (collection.isEmpty()){
System.out.println("Collection is empty");
}
else{
System.out.println( "Collection size: " + size);
}
System.out.println();
// Remove specific data
collection.remove(str2);
System.out.println("After removing [" + str2 + "]\n");
System.out.print("Now collection data: ");
iterator = collection.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();
size = collection.size();
System.out.println("Collection size: " + size + "\n");
//Collection empty
collection.clear();
size = collection.size();
if (collection.isEmpty()){
System.out.println("Collection is empty");
}
else{
System.out.println( "Collection size: " + size);
}
}
}

Download this example.

Output of this program:

C:\vinod\collection>javac
CollectionTest.java

C:\vinod\collection>java
CollectionTest
Collection Example!

Collection data: Blue White


Green Yellow
Collection size: 4

After removing [White]

Now collection data: Blue


Green Yellow
Collection size: 3

Collection is empty

C:\vinod\collection>

Linked List Example

This section discusses an example to demonstrate the various methods of List interface. We are
using two classes ArrayList and LinkedList in the example code. The code below is similar to
the previous example, but it performs many List operations. Lets discuss the example code.

Description of program:

This program helps you in storing the large amount of data as a collection. The LinkedList is a
part of collection that constructs a list containing the elements of the specified collection. Iterator
methods returns the values in the order in which they are stored.

If you want to insert the data in the linkedList then use add() method. The hasNext() method
returns true if the iterator contains more elements and the next() method returns the next element
in the iteration. To insert and remove the data at first, last and specified position in the
linkedList, you use the addFirst(), addLast(), add(), removeFirst(), removeLast() and
remove() methods. To retrieve the element with respect to a specified position use the getFirst(),
getLast() and get() methods.

Here is the code of program:

import java.util.*;
public class LinkedListExample{
public static void main(String[] args) {
System.out.println("Linked List Example!");
LinkedList <Integer>list = new LinkedList<Integer>();
int num1 = 11, num2 = 22, num3 = 33, num4 = 44;
int size;
Iterator iterator;
//Adding data in the list
list.add(num1);
list.add(num2);
list.add(num3);
list.add(num4);
size = list.size();
System.out.print( "Linked list data: ");
//Create a iterator
iterator = list.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");
}
System.out.println();
//Check list empty or not
if (list.isEmpty()){
System.out.println("Linked list is empty");
}
else{
System.out.println( "Linked list size: " + size);
}
System.out.println("Adding data at 1st location: 55");
//Adding first
list.addFirst(55);
System.out.print("Now the list contain: ");
iterator = list.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");
}
System.out.println();
System.out.println("Now the size of list: " + list.size());
System.out.println("Adding data at last location: 66");
//Adding last or append
list.addLast(66);
System.out.print("Now the list contain: ");
iterator = list.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");
}
System.out.println();
System.out.println("Now the size of list: " + list.size());
System.out.println("Adding data at 3rd location: 55");
//Adding data at 3rd position
list.add(2,99);
System.out.print("Now the list contain: ");
iterator = list.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");
}
System.out.println();
System.out.println("Now the size of list: " + list.size());
//Retrieve first data
System.out.println("First data: " + list.getFirst());
//Retrieve lst data
System.out.println("Last data: " + list.getLast());
//Retrieve specific data
System.out.println("Data at 4th position: " + list.get(3));
//Remove first
int first = list.removeFirst();
System.out.println("Data removed from 1st location: " + first);
System.out.print("Now the list contain: ");
iterator = list.iterator();
//After removing data
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");
}
System.out.println();
System.out.println("Now the size of list: " + list.size());
//Remove last
int last = list.removeLast();
System.out.println("Data removed from last location: " + last);
System.out.print("Now the list contain: ");
iterator = list.iterator();
//After removing data
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");
}
System.out.println();
System.out.println("Now the size of list: " + list.size());
//Remove 2nd data
int second = list.remove(1);
System.out.println("Data removed from 2nd location: " + second);
System.out.print("Now the list contain: ");
iterator = list.iterator();
//After removing data
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");
}
System.out.println();
System.out.println("Now the size of list: " + list.size());
//Remove all
list.clear();
if (list.isEmpty()){
System.out.println("Linked list is empty");
}
else{
System.out.println( "Linked list size: " + size);
}
}
}

Download this example.

Output of program:

C:\vinod\collection>javac
LinkedListExample.java

C:\vinod\collection>java
LinkedListExample
Linked List Example!
Linked list data: 11 22 33 44
Linked list size: 4
Adding data at 1st location: 55
Now the list contain: 55 11 22 33
44
Now the size of list: 5
Adding data at last location: 66
Now the list contain: 55 11 22 33
44 66
Now the size of list: 6
Adding data at 3rd location: 55
Now the list contain: 55 11 99 22
33 44 66
Now the size of list: 7
First data: 55
Last data: 66
Data at 4th position: 22
Data removed from 1st location:
55
Now the list contain: 11 99 22 33
44 66
Now the size of list: 6
Data removed from last location:
66
Now the list contain: 11 99 22 33
44
Now the size of list: 5
Data removed from 2nd location:
99
Now the list contain: 11 22 33 44
Now the size of list: 4
Linked list is empty

C:\vinod\collection>

Tree Map Example

In the following example, we have used the TreeMap method, which stores its elements in a tree
and orders its elements based on their values. Here in the example we have used the key of the
element to show the values of the element. To retrieve the keys and values use keySet() and
values() method respectively.

This program shows the data elements left after removing the particular element by specifying its
key. Using the Iterator interface methods, we can traverse a collection from start to finish and
safely remove elements from the underlying Collection.

Here is the code of program:

import java.util.*;

public class TreeMapExample{


public static void main(String[] args) {
System.out.println("Tree Map Example!\n");
TreeMap <Integer, String>tMap = new TreeMap<Integer, String>();
//Addding data to a tree map
tMap.put(1, "Sunday");
tMap.put(2, "Monday");
tMap.put(3, "Tuesday");
tMap.put(4, "Wednesday");
tMap.put(5, "Thursday");
tMap.put(6, "Friday");
tMap.put(7, "Saturday");
//Rerieving all keys
System.out.println("Keys of tree map: " + tMap.keySet());
//Rerieving all values
System.out.println("Values of tree map: " + tMap.values());
//Rerieving the value from key with key number 5
System.out.println("Key: 5 value: " + tMap.get(5)+ "\n");
//Rerieving the First key and its value
System.out.println("First key: " + tMap.firstKey() + " Value: "
+ tMap.get(tMap.firstKey()) + "\n");
//Rerieving the Last key and value
System.out.println("Last key: " + tMap.lastKey() + " Value: "
+ tMap.get(tMap.lastKey()) + "\n");
//Removing the first key and value
System.out.println("Removing first data: "
+ tMap.remove(tMap.firstKey()));
System.out.println("Now the tree map Keys: " + tMap.keySet());
System.out.println("Now the tree map contain: "
+ tMap.values() + "\n");
//Removing the last key and value
System.out.println("Removing last data: "
+ tMap.remove(tMap.lastKey()));
System.out.println("Now the tree map Keys: " + tMap.keySet());
System.out.println("Now the tree map contain: " + tMap.values());
}
}

Download this example.

Output of this program:

C:\vinod\collection>javac TreeMapExample.java

C:\vinod\collection>java TreeMapExample
Tree Map Example!

Keys of tree map: [1, 2, 3, 4, 5, 6, 7]


Values of tree map: [Sunday, Monday, Tuesday, Wednesday,
Thursday, Friday, Saturday]
Key: 5 value: Thursday

First key: 1 Value: Sunday

Last key: 7 Value: Saturday

Removing first data: Sunday


Now the tree map Keys: [2, 3, 4, 5, 6, 7]
Now the tree map contain: [Monday, Tuesday, Wednesday,
Thursday, Friday, Saturday]

Removing last data: Saturday


Now the tree map Keys: [2, 3, 4, 5, 6]
Now the tree map contain: [Monday, Tuesday, Wednesday,
Thursday, Friday]
C:\vinod\collection>

Tree Set Example

In the following example, we have used the TreeSet collection, which is similar to TreeMap
that stores its elements in a tree and maintain order of its elements based on their values. To get
the size of TreeSet collection size() method is used. Our TreeSet collection contains 4 elements
and the size of the TreeSet can be determine by calling size() method.

Similarly, we have used first() and last() to retrieve first and last element present in the TreeSet.
Program also shows the method to remove the element and then display the remaining elements.
To remove all data from the TreeSet, use the clear() method. To determine whether TreeSet is
empty or not use isEmpty() method. If the TreeSet is empty, it displays the message "Tree set is
empty." otherwise it displays the size of TreeSet.

Here is the code of program:

import java.util.*;

public class TreeSetExample{


public static void main(String[] args) {
System.out.println("Tree Set Example!\n");
TreeSet <Integer>tree = new TreeSet<Integer>();
tree.add(12);
tree.add(23);
tree.add(34);
tree.add(45);
Iterator iterator;
iterator = tree.iterator();
System.out.print("Tree set data: ");
//Displaying the Tree set data
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();
//Check impty or not
if (tree.isEmpty()){
System.out.print("Tree Set is empty.");
}
else{
System.out.println("Tree Set size: " + tree.size());
}
//Retrieve first data from tree set
System.out.println("First data: " + tree.first());
//Retrieve last data from tree set
System.out.println("Last data: " + tree.last());
if (tree.remove(30)){
System.out.println("Data is removed from tree set");
}
else{
System.out.println("Data doesn't exist!");
}
System.out.print("Now the tree set contain: ");
iterator = tree.iterator();
//Displaying the Tree set data
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();
System.out.println("Now the size of tree set: " + tree.size());
//Remove all
tree.clear();
if (tree.isEmpty()){
System.out.print("Tree Set is empty.");
}
else{
System.out.println("Tree Set size: " + tree.size());
}
}
}

Download this example.

Output of this program:

C:\vinod\collection>javac
TreeSetExample.java

C:\vinod\collection>java
TreeSetExample
Tree Set Example!

Tree set data: 12 23 34 45


Tree Set size: 4
First data: 12
Last data: 45
Data doesn't exist!
Now the tree set contain: 12 23
34 45
Now the size of tree set: 4
Tree Set is empty.

C:\vinod\collection>

Collection Iterate Example

In this section, you will get the detailed explanation about the hasNext() method of interface
Iterator. We are going to use hasNext() method of interface Iterator in Java. The description of
the code is given below for the usage of the method.

Description of the code:

Here, you will get to know about the hasNext() method through the following java program.
True is return by this method in case the iteration has more elements. This means that if the
iteration has more elements then the hasNext() method will return true rather than throwing an
exception.

In the program code given below, we have taken a string of elements. We have converted this
string of elements into a list of array and then we have applied the hasNext() method which
returns true because there are more elements in the list. Hence we get the following output.

Here is the code of program:

import java.util.*;

public class hasNext{


public static void main (String args[]) {
boolean b;
String elements[] = {"Blue", "Grey", "Teal"};
Set s = new HashSet(Arrays.asList(elements));
Iterator i = s.iterator();
if (b = i.hasNext()){
System.out.println(b);
}
}
}

Output of the program:

C:\unique>javac
hasNext.java

C:\unique>java
hasNext
true

Converting an Array to a Collection

Here is the illustration for the conversion from the an array to a collection. In this section, you
will learn how how to do this. The given example gives you a brief introduction for converting
an array to collection without losing any data or element held by the array.

This program creates an array, that contains all the elements entered by you. This array is
converted into a list (collection). Every value for the separate subscript of the array will be
converted as elements of the list (collection).

Code Description:

Arrays.asList(name):
Above code converts an array to a collection. This method takes the name of the array as a
parameter which has to be converted.

for(String li: list):


This is the for-each loop. There are two arguments mentioned in the loop. In which, first is the
String type variable li another one is the list name which has to be converted. This loop check
each and every elements of the list and store it into the mentioned variable li.

Here is the code of the program:

import java.util.*;
import java.io.*;

public class ArrayToCollection{


public static void main(String args[]) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("How many elements you want to add to the array: ");
int n = Integer.parseInt(in.readLine());
String[] name = new String[n];
for(int i = 0; i < n; i++){
name[i] = in.readLine();
}
List<String> list = Arrays.asList(name); //Array to Collection
for(String li: list){
String str = li;
System.out.print(str + " ");
}
}
}

Implement the Queue in Java

In this section, you will learn how to implement the queue. A queue holds a collection of data or
elements and follows the FIFO ( First In First Out) rule. The FIFO that means which data added
first in the list, only that element can be removed or retrieved first from the list. In other sense,
You can remove or perform operation on that data which had been added first in the Collection
(list). Whenever you need to remove the last added element then you must remove all these
elements which are entered before the certain element.

The given program implements a queue. It takes all elements as input by user. These values are
added to the list and shows first, last and the rest elements present in the list separately. Some
methods and APIs are explained below which have been used in the program for the certain
purposes:

LinkedList<Integer>():
This is the constructor of the LinkedList class. This class is used by importing the java.util.*;
package. This constructor is used for constructing an empty list. It can contain integer types data
in the given program because in the declaration of the LinkedList class type checking has been
used. This is an implementation of the List interface of the Collections Framework. The
LinkeedList class provides inserting and deleting the data to/from the list.

removeFirst():
Above method removes and returns the first element of the list.

removeLast():
Above method removes and returns the last element of the list.

list.isEmpty():
This method checks whether the list is empty or not.

remove():
This method used to remove the elements in the list in a specified sequence.

Here is the code of program:

import java.io.*;
import java.util.*;

public class QueueImplement{


LinkedList<Integer> list;
String str;
int num;
public static void main(String[] args){
QueueImplement q = new QueueImplement();
}
public QueueImplement(){
try{
list = new LinkedList<Integer>();
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader bf = new BufferedReader(ir);
System.out.println("Enter number of elements : ");
str = bf.readLine();
if((num = Integer.parseInt(str)) == 0){
System.out.println("You have entered either zero/null.");
System.exit(0);
}
else{
System.out.println("Enter elements : ");
for(int i = 0; i < num; i++){
str = bf.readLine();
int n = Integer.parseInt(str);
list.add(n);
}
}
System.out.println("First element :" + list.removeFirst());
System.out.println("Last element :" + list.removeLast());
System.out.println("Rest elements in the list :");
while(!list.isEmpty()){
System.out.print(list.remove() + "\t");
}
}
catch(IOException e){
System.out.println(e.getMessage() + " is not a legal entry.");
System.exit(0);
}
}
}

Implementing a Stack in Java

In this section, you will learn how to implement a stack in Java. A Stack is like a bucket in which
you can put elements one-by-one in sequence and retrieve elements from the bucket according to
the sequence of the last entered element. Stack is a collection of data and follows the LIFO (Last
in, first out) rule that mean you can insert the elements one-by-one in sequence and the last
inserted element can be retrieved at once from the bucket. Elements are inserted and retrieved
to/from the stack through the push() and pop() method.
This program implements a stack and follows the LIFO rule. It asks you for the number of
elements which have to be entered in the stack and then it takes elements for insertion in the
stack. All the elements present in the stack are shown from the last inserted element to the first
inserted element.

Stack<Integer>():
Above constructor of the Stack class creates a empty stack which holds the integer type value
which is mention with the creation of stack. The Stack class extends the Vector class and both
classes are implemented from the java.util.*; package.

Stack.push(Object obj):
Above method is used to insert or push the data or element in the stack. It takes an object like:
data or elements and push its onto the top of the stack.

Stack.pop():
This is the method to removes the objects like: data or elements at the top positions of stack.

Here is the code of program:

import java.io.*;
import java.util.*;

public class StackImplement{


Stack<Integer> stack;
String str;
int num, n;
public static void main(String[] args){
StackImplement q = new StackImplement();
}
public StackImplement(){
try{
stack = new Stack<Integer>();
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader bf = new BufferedReader(ir);
System.out.print("Enter number of elements : ");
str = bf.readLine();
num = Integer.parseInt(str);
for(int i = 1; i <= num; i++){
System.out.print("Enter elements : ");
str = bf.readLine();
n = Integer.parseInt(str);
stack.push(n);
}
}
catch(IOException e){}
System.out.print("Retrieved elements from the stack : ");
while (!stack.empty()){
System.out.print(stack.pop() + " ");
}
}
}
Map.Entry Java Interface

Sometimes you need to work with map entry. This can be done using Map.Entry Interface of
Java.

The Map interface's entrySet( ) method returns a set of map . These sets are called as Map.Entry
object.

Methods of Map.Entry Interface


Methods Description

Returns true, if Map.Entry object 's key -value


boolean equals(Object obj)
is equal to the calling object

Object getKey( ) This method returns map entry's key.

Object getValue( ) This method returns map entry's value.

int hashCode( ) This method returns map entry's hash code.

Object setValue(Object v) This method sets the map entry's value to v.

EXAMPLE

Given below example shows you how you can set map entry's value :

import java.util.*;

public class MapEntryDemo {


public static void main(String arghs[]) {
HashMap hmp = new HashMap();
hmp.put("Neha", new Double(2424.34));
hmp.put("Niti", new Double(367.22));
hmp.put("Shivangi", new Double(4381.00));
hmp.put("Vinita", new Double(4761.22));
hmp.put("Sushmita", new Double(3904.08));
// Get a set of the entries
Set set = hmp.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display entries
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
if (me.getKey().equals("Sushmita")) {
me.setValue((Double) me.getValue() + 1000.00);
System.out.println("Sushmita's new balance: " + me.getValue());
}
}
}
}

OUTPUT :

Neha: 2424.34

Sushmita: 3904.08

Sushmita's new balance: 4904.08

Shivangi: 4381.0

Vinita: 4761.22

Collections Class
The java.util.Collections class contains static utility methods for manipulating collections.

Some useful Collections methods

Assume the following declarations have been made, where T is a class or interface type.

int i;
List<? extends T> list;
List<T> listT;
List<?> listO;
Comparator<? super T> comp;
T key;
T t;
Object obj;
Collection<? extends T> coll;

Returns Method Action

Rearranging - Sorting, Shuffling, . . .

sort(listT) Sorts listT. Elements must be Comparable<T>.


Stable, O(N log N).

sort(listT, comp) Sorts listT using a comparator.

shuffle(listO) Puts the elements of listO in random order.


reverse(listO) Reverses the elements of list.

Searching

i = binarySearch(list, key) Searches in list for key. Elements must implement


Comparable<T>. Returns index of element or negative
value if not found. See Binary Search.

i = binarySearch(list, key, comp) Searches in list for key using Comparator comp.
Returns index of element or negative value if not found.
See Binary search.

t = max(coll) Returns maximum valued Comparable object in the


Collection coll.

t = max(coll, comp) Returns maximum valued object in the Collection coll


using Comparator comp.

t = min(coll) Returns minimum valued Comparable object in the


Collection coll.

t = min(coll, comp) Returns minimum valued object in the Collection coll


using Comparator comp.

Generics in java

Anda mungkin juga menyukai