Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Project File

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 52

About The JAVA language

The Creation of Java

Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and
Mike Sheridan at Sun Microsystems, Inc. in 1991. It took 18 months to develop the first working
version. This language was initially called Oak but was renamed Java in 1995. Between the
initial implementation of Oak in the fall of 1992 and the public announcement of Java in the
spring of 1995, many more people contributed to the design and evolution of the language. Bill
Joy, Arthur van Hoff, Jonathan Payne, Frank Yellin, and Tim Lindholm were key contributors to
the maturing of the original prototype.
The original impetus for Java was not the Internet! Instead, the primary motivation was
the need for a platform-independent (that is, architecture neutral) language that could be used to
create software to be embedded in various consumer electronic devices, such as microwave
ovens and remote controls.
About the time that the details of Java were being worked out, a second, and ultimately
more important, factor was emerging that would play a crucial role in the future of Java. This
second force was, of course, the World Wide Web. Had the Web not taken shape at about the
same time that Java was being implemented, Java might have remained a useful but obscure
language for programming consumer electronics. However, with the emergence of the World
Wide Web, Java was propelled to the forefront of computer language design, because the Web,
too, demanded portable programs.
By 1993, it became obvious to members of the Java design team that the problems of
portability frequently encountered when creating code for embedded controllers are also found
when attempting to create code for the Internet. In fact, the same problem that Java was initially
designed to solve on a small scale could also be applied to the Internet on a large scale. This
realization caused the focus of Java to switch from consumer electronics to Internet
programming. So, while the desire for an architecture neutral programming language provided
the initial spark, the Internet ultimately led to Javas large-scale success.

Importance of JAVA

Although the fundamental forces that necessitated the invention of Java are portability
and security, other factors also played an important role in molding the final form of the
language. The key considerations were summed up by the Java team in the following list of
buzzwords:
1. Security
When we use a Java-compatible Web browser, we can safely download Java applets
without fear of viral infection or malicious intent. Java achieves this protection by confining a
Java program to the Java execution environment and not allowing it access to other parts of the
computer. The ability to download applets with confidence that no harm will be done and that no
security will be breached is considered by many to be the single most important aspect of Java.
2. Portability
Many types of computers and operating systems are in use throughout the worldand
many are connected to the Internet. For programs to be dynamically downloaded to all the
various types of platforms connected to the Internet, some means of generating portable
executable code is needed. As you will soon see, the same mechanism that helps ensure security
also helps create portability. Indeed, Javas solution to these two problems is both elegant and
efficient.
3. Simple
Java was designed to be easy for the professional programmer to learn and use
effectively. Assuming that you have some programming experience, you will not find Java hard
to master. If you already understand the basic concepts of object-oriented programming, learning
Java will be even easier.
4. Object-Oriented
Although influenced by its predecessors, Java was not designed to be source-code
compatible with any other language. This allowed the Java team the freedom to design with a
blank slate. One outcome of this was a clean, usable, pragmatic approach to objects. Borrowing
liberally from many seminal object-software environments of the last few decades.
5. Robust
The multiplatform environment of the Web places extraordinary demands on a program,
because the program must execute reliably in a variety of systems. Thus, the ability to create
robust programs was given a high priority in the design of Java. To gain reliability, Java restricts
you in a few key areas, to force you to find your mistakes early in program development. At the
2

same time, Java frees you from having to worry about many of the most common causes of
programming errors. Because Java is a strictly typed language, it checks your code at compile
time. However, it also checks your code at run time.
6. Multithreaded
Java was designed to meet the real-world requirement of creating interactive, networked
programs. To accomplish this, Java supports multithreaded programming, which allows you to
write programs that do many things simultaneously. The Java run-time system comes with an
elegant yet sophisticated solution for multiprocessor synchronization that enables you to
construct smoothly running interactive systems. Javas easy-to-use approach to multithreading
allows you to think about the specific behavior of your program, not the multitasking subsystem.
7. Architecture-Neutral
A central issue for the Java designers was that of code longevity and portability. One of
the main problems facing programmers is that no guarantee exists that if you write a program
today, it will run tomorroweven on the same machine. Operating system upgrades, processor
upgrades, and changes in core system resources can all combine to make a program malfunction.
The Java designers made several hard decisions in the Java language and the Java Virtual
Machine in an attempt to alter this situation. Their goal was write once; run anywhere, any time,
forever. To a great extent, this goal was accomplished.
8. Interpreted and High Performance
Java enables the creation of cross-platform programs by compiling into an intermediate
representation called Java byte code. This code can be interpreted on any system that provides a
Java Virtual Machine. Most previous attempts at cross plat form solutions have done so at the
expense of performance.
9. Distributed
Java is designed for the distributed environment of the Internet, because it handles
TCP/IP protocols. In fact, accessing a resource using a URL is not much different from accessing
a file. The original version of Java (Oak) included features for intraaddress- space messaging.
This allowed objects on two different computers to execute procedures remotely.
10. Dynamic
Java programs carry with them substantial amounts of run-time type information that is
used to verify and resolve accesses to objects at run time. This makes it possible to dynamically
link code in a safe and expedient manner. This is crucial to the robustness of the applet
environment, in which small fragments of bytecode may be dynamically updated on a running
system.

First Simple JAVA Program

/*
This is a simple Java program.
Call this file "Example.java".
*/
class Example {
// Your program begins with a call to main().
public static void main(String args[]) {
System.out.println("This is a simple Java program.");
}
}
Program 1

To compile the Example program, execute the compiler, javac, specifying the name of the
source file on the command line, as shown here:
C:\>javac Example.java
To actually run the program, you must use the Java interpreter, called java. To do so, pass the
class name Example as a command-line argument, as shown here:
C:\>java Example
Output of Program 1:- When the program is run, the following output is displayed: This is a
simple Java program.
When Java source code is compiled, each individual class is put into its own output file
named after the class and using the .class extension. This is why it is a good idea to give your
Java source files the same name as the class they containthe name of the source file will match
the name of the .class file. When you execute the Java interpreter as just shown, you are actually
specifying the name of the class that you want the interpreter to execute. It will automatically
search for a file by that name that has the .class extension. If it finds the file, it will execute the
code contained in the specified class.

Lexical Issues

1. Whitespace
Java is a free-form language. This means that you do not need to follow any special
indentation rules. In Java, whitespace is a space, tab, or newline.
2. Identifiers
Identifiers are used for class names, method names, and variable names. An identifier
may be any descriptive sequence of uppercase and lowercase letters, numbers, or the underscore
and dollar-sign characters. They must not begin with a number, lest they be confused with a
numeric literal.
3. Literals
A constant value in Java is created by using a literal representation of it. For example,
here are some literals:
100
98.6
X
This is a test
4. Separators
In Java, there are a few characters that are used as separators. The most commonly used
separator in Java is the semicolon.
()

Symbol Name
Parentheses

Purpose
Used to contain lists of parameters in method definition
and invocation

{}

Braces

Used to contain the values of automatically initialized


arrays. Also used to define a block of code, for classes,
methods, and local scopes.

[]

Brackets

Semicolon

Used to declare array types. Also


dereferencing array values.
Terminates statements.

Comma

used

when

Separates consecutive identifiers in a variable


declaration. Also used to chain statements together inside
a for statement.

Data Types

Integers
Java defines four integer types: byte, short, int, and long.
Name Width
Range
Long
64
9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Int
32
2,147,483,648 to 2,147,483,647
Short
16
32,768 to 32,767
Byte
8
128 to 127
Table 3: Types of Integers
byte
The smallest integer type is byte. This is a signed 8-bit type that has a range from 128 to
127. Variables of type byte are especially useful when youre working with a stream of data from
a network or file.
short
short is a signed 16-bit type. It has a range from 32,768 to 32,767. It is probably the least-used
Java type, since it is defined as having its high byte first
int
The most commonly used integer type is int. It is a signed 32-bit type that has a range from
2,147,483,648 to 2,147,483,647. In addition to other uses, variables of type int are commonly
employed to control loops and to index arrays.
long
long is a signed 64-bit type and is useful for those occasions where an int type is not large
enough to hold the desired value.
// Compute distance light travels using long variables.
class Light {
public static void main(String args[]) {
int lightspeed;
long days;
long seconds;
long distance;
// approximate speed of light in miles per second
lightspeed = 186000;
days = 1000; // specify number of days here
seconds = days * 24 * 60 * 60; // convert to seconds
distance = lightspeed * seconds; // compute distance
System.out.print("In " + days);
System.out.print(" days light will travel about ");
6

System.out.println(distance + " miles.");


}
}
Program 2
Output: This program generates the following output:
In 1000 days light will travel about 16070400000000 miles.
Floating-Point Types
Floating-point numbers, also known as real numbers, are used when evaluating
expressions that require fractional precision. For example, calculations such as square root, or
transcendentals such as sine and cosine, result in a value whose precision requires a floatingpoint type.
Double
Float

Name Width
64
32

Range
4.9e324 to 1.8e+308
1.4e045 to 3.4e+038
Table 4: Types of Floating-Point

Each of these floating-point types is examined next.


float
The type float specifies a single-precision value that uses 32 bits of storage. Single
precision is faster on some processors and takes half as much space as double precision, but will
become imprecise when the values are either very large or very small.
double
Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double
precision is actually faster than single precision on some modern processors that have been
optimized for high-speed mathematical calculations.
// Compute the area of a circle.
class Area {
public static void main(String args[]) {
double pi, r, a;
r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area
System.out.println("Area of circle is " + a);
}
}
Program 3

Characters
In Java, the data type used to store characters is char. However, C/C++ programmers beware:
char in Java is not the same as char in C or C++. In C/C++, char is an integer type that is 8 bits
wide. This is not the case in Java. Instead, Java uses Unicode to represent characters. Unicode
defines a fully international character set that can represent all of the characters found in all
human languages.
// char variables behave like integers.
class CharDemo2 {
public static void main(String args[]) {
char ch1;
ch1 = 'X';
System.out.println("ch1 contains " + ch1);
ch1++; // increment ch1
System.out.println("ch1 is now " + ch1);
}
}
Program 4
Output: The output generated by this program is shown here:
ch1 contains X
ch1 is now Y
Booleans
Java has a simple type, called boolean, for logical values. It can have only one of two possible
values, true or false
// Demonstrate boolean values.
class BoolTest {
public static void main(String args[]) {
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
// a boolean value can control the if statement
if(b) System.out.println("This is executed.");
b = false;
if(b) System.out.println("This is not executed.");
// outcome of a relational operator is a boolean value
System.out.println("10 > 9 is " + (10 > 9));
}
}
Program 5

Variables

The variable is the basic unit of storage in a Java program. A variable is defined by the
combination of an identifier, a type, and an optional initializer.
Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form of a variable
declaration is shown here:
type identifier [ = value][, identifier [= value] ...] ;
The type is one of Javas atomic types, or the name of a class or interface. The identifier is the
name of the variable.
// Demonstrate lifetime of a variable.
class LifeTime {
public static void main(String args[]) {
int x;
for(x = 0; x < 3; x++) {
int y = -1; // y is initialized each time block is entered
System.out.println("y is: " + y); // this always prints -1
y = 100;
System.out.println("y is now: " + y);
}
}
}
Program 6
Output: The output generated by this program is shown here:
y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100

Arrays

An array is a group of like-typed variables that are referred to by a common name.


Arrays of any type can be created and may have one or more dimensions.
One-Dimensional Arrays
A one-dimensional array is, essentially, a list of like-typed variables.The general form of
a one-dimensional array declaration is
type var-name[ ];
// Average an array of values.
class Average {
public static void main(String args[]) {
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
int i;
for(i=0; i<5; i++)
result = result + nums[i];
System.out.println("Average is " + result / 5);
}
}
Program 7
Multidimensional Arrays
In Java, multidimensional arrays are actually arrays of arrays. There are a couple of
subtle differences. To declare a multidimensional array variable, specify each additional index
using another set of square brackets
// Manually allocate differing size second dimensions.
class TwoDAgain {
public static void main(String args[]) {
int twoD[][] = new int[4][];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<i+1; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<i+1; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}Program 8
10

Operators

Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way that they are
used in algebra. The following table lists the arithmetic operators:
Operator

*
/
%
++
+=
=
*=
/=
%=

Result
Addition
Subtraction (also unary minus)
Multiplication
Division
Modulus
Increment
Addition assignment
Subtraction assignment
Multiplication assignment
Division assignment
Modulus assignment
Decrement
Table 5: Arithmetic operators

The Bitwise Operators


Java defines several bitwise operators which can be applied to the integer types, long,
int, short, char, and byte. These operators act upon the individual bits of their operands.
They are summarized in the following table:
Operator
~
|
&
^
>>
>>>
<<
&=
|=

Result
Bitwise unary NOT
Bitwise OR
Bitwise AND
Bitwise exclusive OR
Shift right
Shift right zero fill
Shift left
Bitwise AND assignment
Bitwise OR assignment
Table 6: Bitwise operators

11

Control Statements

Javas Selection Statements


Java supports two selection statements: if and switch. These statements allow you to
control the flow of your programs execution based upon conditions known only during run time.
1. if
The if statement is Javas conditional branch statement. It can be used to route program
execution through two different paths. Here is the general form of the if statement:
if (condition) statement1;
else statement2;
2. Nested ifs
A nested if is an if statement that is the target of another if or else. Nested ifs are very
common in programming. When you nest ifs, the main thing to remember is that an else
statement always refers to the nearest if statement that is within the same block as the else and
that is not already associated with an else.
3. The if-else-if Ladder
A common programming construct that is based upon a sequence of nested ifs is the ifelse-if ladder. It looks like this:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;
// Demonstrate if-else-if statements.
class IfElse {
public static void main(String args[]) {
int month = 4; // April
String season;
if(month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
12

season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";
System.out.println("April is in the " + season + ".");
}
}
Program 9
Output: Here is the output produced by the program:
April is in the Spring.
4. switch
The switch statement is Javas multiway branch statement. It provides an easy way to
dispatch execution to different parts of your code based on the value of an expression. As such, it
often provides a better alternative than a large series of if-else-if statements. Here is the general
form of a switch statement:
switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...
case valueN:
// statement sequence
break;
default:
// default statement sequence
}
// A simple example of the switch.
class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<6; i++)
switch(i) {
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
13

break;
case 2:
System.out.println("i is two.");
break;
case 3:
System.out.println("i is three.");
break;
default:
System.out.println("i is greater than 3.");
}
}
}
Program: 10
Output: The output produced by this program is shown here:
i is zero.
i is one.
i is two.
i is three.
i is greater than 3.
i is greater than 3.
Iteration Statements
Javas iteration statements are for, while, and do-while. These statements create what we
commonly call loops.
1. while
The while loop is Javas most fundamental looping statement. It repeats a statement or
block while its controlling expression is true. Here is its general form:
while(condition) {
// body of loop
}
// Demonstrate the while loop.
class While {
public static void main(String args[]) {
int n = 10;
while(n > 0) {
System.out.println("tick " + n);
n--;
}
}
}
Program: 11
14

Output: When you run this program, it will tick ten times:
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1

2. do-while
The do-while loop always executes its body at least once, because its conditional
expression is at the bottom of the loop. Its general form is
do {
// body of loop
} while (condition);
3. for
It is a powerful and versatile construct. Here is the general form of the for statement:
for(initialization; condition; iteration) {
// body
}
If only one statement is being repeated, there is no need for the curly braces.
// Demonstrate the for loop.
class ForTick {
public static void main(String args[]) {
int n;
for(n=10; n>0; n--)
System.out.println("tick " + n);
}
}
Program :12

15

Classes

The class is at the core of Java. It is the logical construct upon which the entire Java
language is built because it defines the shape and nature of an object. As such, the class forms the
basis for object-oriented programming in Java. Any concept you wish to implement in a Java
program must be encapsulated within a class.
The General Form of a Class
When you define a class, you declare its exact form and nature. You do this by specifying
the data that it contains and the code that operates on that data. While very simple classes may
contain only code or only data, most real-world classes contain both. As you will see, a class
code defines the interface to its data.
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodnameN(parameter-list) {
// body of method
}
}
/* A program that uses the Box class.
Call this file BoxDemo.java
*/
class Box {
double width, height, depth;
}
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
// assign values to mybox's instance variables
mybox.width = 10; mybox.height = 20;
mybox.depth = 15; // compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}}
Program :13

16

Objects

Declaring Objects
When you create a class, you are creating a new data type. You can use this type to
declare objects of that type. However, obtaining objects of a class is a two-step process. First,
you must declare a variable of the class type. This variable does not define an object. Instead, it
is simply a variable that can refer to an object. Second, you must acquire an actual, physical copy
of the object and assign it to that variable. You can do this using the new operator. In the
preceding sample programs, a line similar to the following is used to declare an object of type
Box:
Box mybox = new Box();
This statement combines the two steps just described. It can be rewritten like this to
show each step more clearly:
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object

Constructors
It can be tedious to initialize all of the variables in a class each time an instance is
created.Even when you add convenience functions the class in which it resides and is
syntactically similar to a method. Once defined, the constructor is automatically called
immediately after the object is created, before the new operator completes. Constructors look a
little strange because they have no return type, not even void. This is because the implicit return
type of a class constructor is the class type itself.This version is shown here:
/* Here, Box uses a constructor to initialize the
dimensions of a box.
*/
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
// compute and return volume
double volume() {
return width * height * depth;
17

}
}
class BoxDemo6 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Program: 14
Output: When this program is run, it generates the following results:
Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0

The this Keyword


Sometimes a method will need to refer to the object that invoked it. To allow this, Java
defines the this keyword. this can be used inside any method to refer to the current object. That
is, this is always a reference to the object on which the method was invoked. You can use this
anywhere a reference to an object of the current class type is permitted.
To better understand what this refers to, consider the following version of Box( ):
// A redundant use of this.
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}

18

Constructor and Method Overloading

Overloading Methods
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.
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.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
Program: 15
Output: This program generates the following output:
19

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

Overloading Constructors
In addition to overloading normal methods, you can also overload constructor methods.
In fact, for most real-world classes that you create, overloaded constructors will be the norm, not
the exception Following is the latest version of Box:
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
Program: 16

Using Objects as Parameters


So far we have only been using simple types as parameters to methods. However, it is
both correct and common to pass objects to methods.
For example, the following version of Box allows one object to initialize another:
// Here, Box allows one object to initialize another.
class Box {
double width;
double height;
double depth;
// construct clone of an object
Box(Box ob) { // pass object to constructor
20

width = ob.width;
height = ob.height;
depth = ob.depth;
}// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
class OverloadCons2 {
public static void main(String args[]) {
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
Box myclone = new Box(mybox1);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
HE JAVA LANGUAGE
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of cube is " + vol);
// get volume of clone
vol = myclone.volume();
System.out.println("Volume of clone is " + vol);
}Program: 17
21

Inheritance

Inheritance is one of the cornerstones of object-oriented programming because it allows


the creation of hierarchical classifications. Using inheritance, you can create a general class that
defines traits common to a set of related items. This class can then be inherited by other, more
specific classes, each adding those things that are unique to it. In the terminology of Java, a class
that is inherited is called a superclass. The class that does the inheriting is called a subclass.
Inheritance Basics
To inherit a class, you simply incorporate the definition of one class into another by using
the extends keyword. To see how, lets begin with a short example. The following program
creates a superclass called A and a subclass called B. Notice how the keyword extends is used to
create a subclass of A.
// A simple example of inheritance.
// Create a superclass.
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A();
B subOb = new B();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
/* The subclass has access to all public members of
its superclass. */
subOb.i = 7;
22

subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}
Program: 18
Output: The output from this program is shown here:
Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24

Member Access and Inheritance


Although a subclass includes all of the members of its superclass, it cannot access those
members of the superclass that have been declared as private.
// This program uses inheritance to extend Box.
class Box {
double width;
double height;
double depth;
// construct clone of an object
Box(Box ob) { // pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
23

width = -1; // use -1 to indicate


height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
// Here, Box is extended to include weight.
class BoxWeight extends Box {
double weight; // weight of box
// constructor for BoxWeight
BoxWeight(double w, double h, double d, double m) {
width = w;
height = h;
depth = d;
weight = m;
}
}
class DemoBoxWeight {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
System.out.println("Weight of mybox2 is " + mybox2.weight);
}
}
Program: 19
Output: The output from this program is shown here:
Volume of mybox1 is 3000.0
Weight of mybox1 is 34.3
Volume of mybox2 is 24.0
Weight of mybox2 is 0.076

24

Using super
There would be no way for a subclass to directly access or initialize these variables on its
own. Since encapsulation is a primary attribute of OOP, it is not surprising that Java provides a
solution to this problem. Whenever a subclass needs to refer to its immediate superclass, it can
do so by use of the keyword super.
// A complete implementation of BoxWeight.
class Box {
private double width;
private double height;
private double depth;
// construct clone of an object
Box(Box ob) { // pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
// BoxWeight now fully implements all constructors.
class BoxWeight extends Box {
double weight; // weight of box
// construct clone of an object
BoxWeight(BoxWeight ob) { // pass object to constructor
super(ob);
weight = ob.weight;
25

}
// constructor when all parameters are specified
BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
}
// default constructor
BoxWeight() {
super();
weight = -1;
}
// constructor used when cube is created
BoxWeight(double len, double m) {
super(len);
weight = m;
}
}
class DemoSuper {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
BoxWeight mybox3 = new BoxWeight(); // default
BoxWeight mycube = new BoxWeight(3, 2);
BoxWeight myclone = new BoxWeight(mybox1);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
System.out.println("Weight of mybox2 is " + mybox2.weight);
System.out.println();
vol = mybox3.volume();
System.out.println("Volume of mybox3 is " + vol);
System.out.println("Weight of mybox3 is " + mybox3.weight);
System.out.println();
vol = myclone.volume();
System.out.println("Volume of myclone is " + vol);
System.out.println("Weight of myclone is " + myclone.weight);
System.out.println();
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
System.out.println("Weight of mycube is " + mycube.weight);
System.out.println();
}Program: 20
26

Output: This program generates the following output:


Volume of mybox1 is 3000.0
Weight of mybox1 is 34.3
Volume of mybox2 is 24.0
Weight of mybox2 is 0.076
Volume of mybox3 is -1.0
Weight of mybox3 is -1.0
Volume of myclone is 3000.0
Weight of myclone is 34.3
Volume of mycube is 27.0
Weight of mycube is 2.0
Creating a Multilevel Hierarchy
We can build hierarchies that contain as many layers of inheritance as you like. As
mentioned, it is perfectly acceptable to use a subclass as a superclass of another. For example,
given three classes called A, B, and C, C can be a subclass of B, which is a subclass of A. When
this type of situation occurs, each subclass inherits all of the traits found in all of its superclasses.
In this case, C inherits all aspects of B and A. To see how a multilevel hierarchy can be useful,
consider the following program. In it, the subclass BoxWeight is used as a superclass to create
the subclass called Shipment. Shipment inherits all of the traits of BoxWeight and Box, and
adds a field called cost, which holds the cost of shipping such a parcel.
// Extend BoxWeight to include shipping costs.
// Start with Box.
class Box {
private double width;
private double height;
private double depth;
// construct clone of an object
Box(Box ob) { // pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
27

depth = -1; // box


}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
// Add weight.
class BoxWeight extends Box {
double weight; // weight of box
// construct clone of an object
BoxWeight(BoxWeight ob) { // pass object to constructor
super(ob);
weight = ob.weight;
}
// constructor when all parameters are specified
BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
}
// default constructor
BoxWeight() {
super();
weight = -1;
}
// constructor used when cube is created
BoxWeight(double len, double m) {
super(len);
weight = m;
}
}
// Add shipping costs
class Shipment extends BoxWeight {
double cost;
super();
cost = -1;
}
// constructor used when cube is created
Shipment(double len, double m, double c) {
super(len, m);
cost = c;
}
28

}
class DemoShipment {
public static void main(String args[]) {
Shipment shipment1 =
new Shipment(10, 20, 15, 10, 3.41);
Shipment shipment2 =
new Shipment(2, 3, 4, 0.76, 1.28);
double vol;
vol = shipment1.volume();
+ shipment1.weight);
System.out.println("Shipping cost: $" + shipment1.cost);
System.out.println();
vol = shipment2.volume();
System.out.println("Volume of shipment2 is " + vol);
System.out.println("Weight of shipment2 is "
+ shipment2.weight);
System.out.println("Shipping cost: $" + shipment2.cost);
}
}
Program: 21
Output: The output of this program is shown here:
Volume of shipment1 is 3000.0
Weight of shipment1 is 10.0
Shipping cost: $3.41
Volume of shipment2 is 24.0
Weight of shipment2 is 0.76
Shipping cost: $1.28
Method Overriding
In a class hierarchy, when a method in a subclass has the same name and type signature
as a method in its superclass, then the method in the subclass is said to override the method in
the superclass. When an overridden method is called from within a subclass, it will always refer
to the version of that method defined by the subclass. The version of the method defined by the
superclass will be hidden. Consider the following:
// Method overriding.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
29

System.out.println("i and j: " + i + " " + j);


}
}
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// display k this overrides show() in A
void show() {
System.out.println("k: " + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
Program: 22
Output: The output produced by this program is shown here:
k: 3

30

Packages and Interfaces

Packages and interfaces are two of the basic components of a Java program. In general, a
Java source file can contain any (or all) of the following four internal parts:
A single package statement (optional)
Any number of import statements (optional)
A single public class declaration (required)
Any number of classes private to the package (optional)

Packages
To create a package is quite easy: simply include a package command as the first
statement in a Java source file. Any classes declared within that file will belong to the specified
package. The package statement defines a name space in which classes are stored. If you omit
the package statement, the class names are put into the default package, which has no name.
(This is why you havent had to worry about packages before now.) While the default package is
fine for short, sample programs, it is inadequate for real applications. Most of the time, you will
define a package for your code.
This is the general form of the package statement:
package pkg;
Here, pkg is the name of the package. For example, the following statement creates a
package called MyPackage.
package MyPackage;

A Short Package Example


Keeping the preceding discussion in mind, you can try this simple package:
// A simple package
package MyPack;
class Balance {
String name;
double bal;
Balance(String n, double b) {
name = n;
bal = b;
}
void show() {
if(bal<0)
System.out.print("--> ");
31

System.out.println(name + ": $" + bal);


}
}
class AccountBalance {
public static void main(String args[]) {
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for(int i=0; i<3; i++) current[i].show();
}
}
Program: 22
Call this file AccountBalance.java, and put it in a directory called MyPack. Next,
compile the file. Make sure that the resulting .class file is also in the MyPack directory. Then try
executing the AccountBalance class, using the following command line:
java MyPack.AccountBalance
Remember, you will need to be in the directory above MyPack when you execute this
command, or to have your CLASSPATH environmental variable set appropriately. As explained,
AccountBalance is now part of the package MyPack. This means that it cannot be executed by
itself. That is, you cannot use this command line:
java AccountBalance
AccountBalance must be qualified with its package name.
Interfaces
Using the keyword interface, you can fully abstract a class interface from its implementation. In
practice, this means that you can define interfaces which dont make assumptions about how they
are implemented. Once it is defined, any number of classes can implement an interface. Also,
one class can implement any number of interfaces.
Defining an Interface
An interface is defined much like a class. This is the general form of an interface:
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
return-type method-nameN(parameter-list);
type final-varnameN = value;
32

Exception Handling

Java exception handling is managed via five keywords: try, catch, throw, throws, and
finally. Briefly, here is how they work. Program statements that you want to monitor for
exceptions are contained within a try block. If an exception occurs within the try block, it is
thrown.
This is the general form of an exception-handling block:
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed before try block ends
}
Uncaught Exceptions
Before you learn how to handle exceptions in your program, it is useful to see what
happens when you dont handle them. This small program includes an expression that
intentionally causes a divide-by-zero error.
class Exc0 {
public static void main(String args[]) {
int d = 0;
int a = 42 / d;
}
}
Program: 23

Using try and catch


Although the default exception handler provided by the Java run-time system is useful for
debugging, you will usually want to handle an exception yourself. Doing so provides two
benefits. First, it allows you to fix the error. Second, it prevents the program from automatically
terminating.

33

class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
Program: 24
Output: This program generates the following output:
Division by zero.
After catch statement.

Multiple catch Clauses


In some cases, more than one exception could be raised by a single piece of code. To handle this
type of situation, you can specify two or more catch clauses, each catching a different type of
exception. When an exception is thrown, each catch statement is inspected in order, and the first
one whose type matches that of the exception is executed. After one catch statement executes,
the others are bypassed, and execution continues after the try/catch block. The following
example traps two different exception types:
// Demonstrate multiple catch statements.
class MultiCatch {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
34

}
Program: 25
Output: Here is the output generated by running it both ways:
C:\>java MultiCatch
a=0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
C:\>java MultiCatch TestArg
a=1
Array index oob: java.lang.ArrayIndexOutOfBoundsException
After try/catch blocks.

Nested try Statements


The try statement can be nested. That is, a try statement can be inside the block of another try.
Each time a try statement is entered, the context of that exception is pushed on the stack. If an
inner try statement does not have a catch handler for a particular exception, the stack is
unwound and the next try statements catch handlers are inspected for a match.
// An example of nested try statements.
class NestTry {
public static void main(String args[]) {
try {
int a = args.length;
int b = 42 / a;
System.out.println("a = " + a);
try { // nested try block
/* If one command-line arg is used,
then a divide-by-zero exception
will be generated by the following code. */
if(a==1) a = a/(a-a); // division by zero
/* If two command-line args are used,
then generate an out-of-bounds exception. */
if(a==2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
35

}
}
Program: 26
Output: C:\>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One
a=1
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One Two
a=2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException
Creating Your Own Exception Subclasses
Although Javas built-in exceptions handle most common errors, you will probably want to
create your own exception types to handle situations specific to your applications. This is quite
easy to do: just define a subclass of Exception (which is, of course, a subclass of Throwable).
Your subclasses dont need to actually implement anythingit is their existence in the type
system that allows you to use them as exceptions.
// This program creates a custom exception type.
class MyException extends Exception {
private int detail;
MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}
}
class ExceptionDemo {
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[]) {
try {
compute(1);
compute(20);
} catch (MyException e) {System.out.println("Caught " + e);}Program: 27

36

Data Flow Diagram

Level 0Year
Storage

Process
Month

Level 1Default year and date

Data entered

Validity
of Data
entered
Displayed
Informatio
n
Generate
the
Calendar

Generated Information
General Information

37

Code of the project

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.Calendar;
//************************************************************
public class MyCalendar extends JFrame implements ActionListener,ItemListener {
String months[] = {
"Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"};
JLabel jl;
JTextField year;
String y,s="Jan";
JLabel
blank1,blank2,blank3,blank4,blank5,blank6,blank7,blank8,blank9,blank10,blank11,blank
12;
JLabel sun,mon,tue,wed,thu,fri,sat;
GridLayout g1;
GridLayout g2;
JPanel p1=new JPanel();
JPanel p2=new JPanel();
Container c = getContentPane();
int ye=2006;
int d=0,yl,l=0,inc=0;
JLabel date[]=new JLabel[42];
//*************************************************************
public MyCalendar()
{
super("Calendar");
setSize(280,400);
repaint();
setForeground(Color.red);
JLabel yearp = new JLabel("Year: ", JLabel.RIGHT);
JLabel monthp = new JLabel("Month: ", JLabel.RIGHT);
Calendar calendar = Calendar.getInstance();
sun=new JLabel("SUN");
mon=new JLabel("MON");
38

tue=new JLabel("TUE");
wed=new JLabel("WED");
thu=new JLabel("THU");
fri=new JLabel("FRI");
sat=new JLabel("SAT");
s=months[calendar.get(Calendar.MONTH)];
ye=calendar.get(Calendar.YEAR);
for(int i=0;i<31;i++)
{
date[i]=new JLabel(""+(i+1));
}
for(int i=31;i<42;i++)
{
date[i]=new JLabel(" ");
}
jl = new JLabel("January");
JComboBox jc = new JComboBox();
year = new JTextField(""+ye,4);
blank1=new JLabel(" ");
blank2=new JLabel(" ");
blank3=new JLabel(" ");
blank4=new JLabel(" ");
blank5=new JLabel(" ");
blank6=new JLabel(" ");
blank7=new JLabel(" ");
blank8=new JLabel(" ");
blank9=new JLabel(" ");
blank10=new JLabel(" ");
blank11=new JLabel(" ");
blank12=new JLabel(" ");
g1=new GridLayout(3,4);
g2=new GridLayout(7,9);
p1.setLayout(g1);
p2.setLayout(g2);
year.addActionListener(this);
jc.addItem("Jan");
jc.addItem("Feb");
jc.addItem("Mar");
jc.addItem("Apr");
jc.addItem("May");
jc.addItem("Jun");
jc.addItem("Jul");
jc.addItem("Aug");
39

jc.addItem("Sep");
jc.addItem("Oct");
jc.addItem("Nov");
jc.addItem("Dec");
jc.addItemListener(this);
jc.setSelectedItem(s);
p1.add(blank3);
p1.add(blank7);
p1.add(blank8);
p1.add(blank2);
p1.add(yearp);
p1.add(year);
p1.add(monthp);
p1.add(jc);
p1.add(blank4);
p1.add(blank5);
p1.add(blank6);
p1.add(blank1);
p2.add(sun);
p2.add(mon);
p2.add(tue);
p2.add(wed);
p2.add(thu);
p2.add(fri);
p2.add(sat);
setVisible(true);
for(int i=0;i<42;i++)
{
p2.add(date[i]);
}
c.setLayout(new BorderLayout());
c.add(p1, BorderLayout.NORTH);
c.add(p2,BorderLayout.CENTER);
calDate();
setVisible(true);
}
//*************************************************************
public void case1()
{
date[0].setText(" ");
for(int i=1;i<32;i++)
40

{
date[i].setText(""+i);
}
for(int i=32;i<42;i++)
date[i].setText(" ");
if(s=="Feb")
{
if(inc==0)
date[29].setText(" ");
date[30].setText(" ");
date[31].setText(" ");
}
if(s=="Apr"||s=="Jun"||s=="Sep"||s=="Nov")
date[31].setText(" ");
}
//***************************************************************
public void case2()
{
date[0].setText(" ");
date[1].setText(" ");
for(int i=2;i<33;i++)
{
date[i].setText(""+(i-1));
}
for(int i=33;i<42;i++)
date[i].setText(" ");
if(s=="Feb")
{
if(inc==0)
date[30].setText(" ");
date[31].setText(" ");
date[32].setText(" ");
}
if(s=="Apr"||s=="Jun"||s=="Sep"||s=="Nov")
date[32].setText(" ");
}
//***************************************************************
public void case3()
{
41

for(int i=0;i<3;i++)
date[i].setText(" ");
for(int i=3;i<34;i++)
{
date[i].setText(""+(i-2));
}
for(int i=34;i<42;i++)
date[i].setText(" ");
if(s=="Feb")
{
if(inc==0)
date[31].setText(" ");
date[32].setText(" ");
date[33].setText(" ");
}
if(s=="Apr"||s=="Jun"||s=="Sep"||s=="Nov")
date[33].setText(" ");
}
//***************************************************************
public void case4()
{
for(int i=0;i<4;i++)
date[i].setText(" ");
for(int i=4;i<35;i++)
{
date[i].setText(""+(i-3));
}
for(int i=35;i<42;i++)
date[i].setText(" ");
if(s=="Feb")
{
if(inc==0)
date[32].setText(" ");
date[33].setText(" ");
date[34].setText(" ");
}
if(s=="Apr"||s=="Jun"||s=="Sep"||s=="Nov")
date[34].setText(" ");
}
//***************************************************************

42

public void case5()


{
for(int i=0;i<5;i++)
date[i].setText(" ");
for(int i=5;i<36;i++)
{
date[i].setText(""+(i-4));
}
for(int i=36;i<42;i++)
date[i].setText(" ");
if(s=="Feb")
{
if(inc==0)
date[33].setText(" ");
date[34].setText(" ");
date[35].setText(" ");
}
if(s=="Apr"||s=="Jun"||s=="Sep"||s=="Nov")
date[35].setText(" ");
}
//***************************************************************
public void case6()
{
for(int i=0;i<6;i++)
date[i].setText(" ");
for(int i=6;i<37;i++)
{
date[i].setText(""+(i-5));
}
for(int i=37;i<42;i++)
date[i].setText(" ");
if(s=="Feb")
{
if(inc==0)
date[34].setText(" ");
date[35].setText(" ");
date[36].setText(" ");
}
if(s=="Apr"||s=="Jun"||s=="Sep"||s=="Nov")
date[36].setText(" ");
}

43

//*************************************************************
public void case0()
{
for(int i=0;i<31;i++)
{
date[i].setText(""+(i+1));
}
for(int i=31;i<42;i++)
date[i].setText(" ");
if(s=="Feb")
{
if(inc==0)
date[28].setText(" ");
date[29].setText(" ");
date[30].setText(" ");
}
if(s=="Apr"||s=="Jun"||s=="Sep"||s=="Nov")
date[30].setText(" ");
}
//************************************************************
public void calDate()
{
if(ye<0||ye>9999)
{
JOptionPane.showMessageDialog(null,"Year should be between 0000 to 9999");
year.setText("2006");
ye=2006;
}
int g=ye;
ye=ye%400;
if(ye%100!=0)
d=(((ye%100-1)/4)+ye%100)%7;
else
d=0;
if((ye/100)%4==0)
d+=1;
if(ye%400==0)
d-=1;
l=(ye%400)/100;
switch(l)
{
case 0:
d=d%7;
break;
44

case 1:
d=(d+6)%7;
break;
case 2:
d=(d+4)%7;
break;
case 3:
d=(d+2)%7;
break;
}
inc=0;
if(g%4==0)
{
if(g%100==0&&g%400==0)
inc=1;
else if(g%100!=0)
inc=1;
else
inc=0;
}
if(s=="Jan")
d=d%7;
if(s=="Feb")
d=(d+31)%7;
if(s=="Mar")
d=(d+31+28+inc)%7;
if(s=="Apr")
d=(d+31+28+31+inc)%7;
if(s=="May")
d=(d+31+28+31+30+inc)%7;
if(s=="Jun")
d=(d+31+28+31+30+31+inc)%7;
if(s=="Jul")
d=(d+31+28+31+30+31+30+inc)%7;
if(s=="Aug")
d=(d+31+28+31+30+31+30+31+inc)%7;
if(s=="Sep")
d=(d+31+28+31+30+31+30+31+31+inc)%7;
if(s=="Oct")
d=(d+31+28+31+30+31+30+31+31+30+inc)%7;
if(s=="Nov")
d=(d+31+28+31+30+31+30+31+31+30+31+inc)%7;
if(s=="Dec")
d=(d+31+28+31+30+31+30+31+31+30+31+30+inc)%7;
switch(d)
{
45

case 0:
case6();
break;
case 1:
case0();
break;
case 2:
case1();
break;
case 3:
case2();
break;
case 4:
case3();
break;
case 5:
case4();
break;
case 6:
case5();
break;
}
}
//***************************************************************
public Insets getInsets() {
return new Insets(10, 10, 5, 5);
}
//*************************************************************
public void actionPerformed(ActionEvent ae) {
y=year.getText();
ye=Integer.parseInt(y);
calDate();
}
//**************************************************************

public void itemStateChanged(ItemEvent ie) {


s = (String)ie.getItem();
y=year.getText();
ye=Integer.parseInt(y);

46

calDate();
}
//***************************************************************
public static void main(String args[])
{
MyCalendar t=new MyCalendar();
}
}

47

Introduction of the project

This is a special quality project in which the user can find the information about the
calendar of any year from 0000AD to 9999AD, so it is the great program and gives the actual
date and day information. It is a 10,000 years calendar so it is more advanced.
The main advantage of this project is that it is better than Windows in-built Calendar
project because in that only 120 years (from 1980 to 2099AD) calendar. So if we want the
calendar of 1900AD then there is a problem. But my project solves the problem and gives the
information about the 10,000 years calendar. Now you can find the Calendar of any year.
Other advantages of this project are that it is based on the Graphics and it is very
simple to use. The advantage of this project is that it gives the current month and year by default.
So it provides more facility than the previous programs.
So enjoy JAVA and enjoy the Calendar.

Name of the project

10,000 years Calendar

Language used

Java language

Number of line of code

About 450 lines

Number of days of completion

5 days

Base

GUI based

Connectivity

System time connectivity

48

Features of the project

Packages used
java.awt-This package is imported because it contains the GUI window tools and as I use the
package because I extended JFrame for this project
java.awt.event-This package is used for the event handling of the GUI window tools as JButton,
JLabel etc. so this package is used for this.
javax.swing-This is the basic package that is used for the Importing the swing components as it
is known that swing is the extended class of the awt so it is used for the advanced programming
on the swing components.
javax.swing.event-This package is used for the event handling on the swing components.
Java.util.Calendar- This is the package that is used to make the connectivity of the program to
the system time that is used to know the current Year, Month, Date, even the Hour, Minute and
the second also.

Default window
If the user do not select any year and any type then the program show the current Month calendar
as a default as shown below:
How to select the month and year for desired output
The given window shows how to select the month and
tear for the desired output:

49

Any year from 0000AD to 9999AD


You can select any year from 0000AD to 9999AD, so it is the great GUI calendar of 10,000
years.

If the user enter the year that is out of the limit


If the user enters the year that is out of the limit then the following message is to be displayed
and the default month and year is to be displayed.
50

51

BIBLIOGRAPHY
INTERNET:

1) www.google.co.in
2) http://www.vogella.com/tutorials/JavaIntroduction/article.html

BOOK:

Programming with java

E.Balagurusamy

52

You might also like