Project File
Project File
Project File
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.
/*
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
[]
Brackets
Semicolon
Comma
used
when
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
Name Width
64
32
Range
4.9e324 to 1.8e+308
1.4e045 to 3.4e+038
Table 4: Types of Floating-Point
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
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
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
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
18
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
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
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
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
}
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
30
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;
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
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.
}
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.
}
}
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
Level 0Year
Storage
Process
Month
Data entered
Validity
of Data
entered
Displayed
Informatio
n
Generate
the
Calendar
Generated Information
General Information
37
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
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();
}
//**************************************************************
46
calDate();
}
//***************************************************************
public static void main(String args[])
{
MyCalendar t=new MyCalendar();
}
}
47
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.
Language used
Java language
5 days
Base
GUI based
Connectivity
48
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
51
BIBLIOGRAPHY
INTERNET:
1) www.google.co.in
2) http://www.vogella.com/tutorials/JavaIntroduction/article.html
BOOK:
E.Balagurusamy
52