Anda di halaman 1dari 35

INTRODUCTION

Java

programming language was originally developed by Sun Microsystems which was


initiated by James Gosling and released in 1995 as core component of Sun Microsystems
Java platform (Java 1.0 [J2SE]). As of December 2008, the latest release of the Java Standard
Edition is 6 (J2SE). With the advancement of Java and its widespread popularity, multiple
configurations were built to suite various types of platforms. Ex: J2EE for Enterprise
Applications, J2ME for Mobile Applications. Sun Microsystems has renamed the new J2
versions as Java SE, Java EE and Java ME, respectively. Java is guaranteed to be Write
Once, Run Anywhere.
Java is:
Object Oriented: In Java, everything is an Object. Java can be easily extended since it is
based on the Object model.
Platform independent: Unlike many other programming languages including C and C++,
when Java is compiled, it is not compiled into platform specific machine, rather into platform
independent byte code. This byte code is distributed over the web and interpreted by virtual
Machine (JVM) on whichever platform it is being run.
Simple: Java is designed to be easy to learn. If you understand the basic concept of OOP,
Java would be easy to master.
Secure: With Java's secure feature, it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption.
Architectural-neutral: Java compiler generates an architecture-neutral object file format,
which makes the compiled code to be executable on many processors, with the presence of
Java runtime system.
Portable: Being architectural-neutral and having no implementation dependent aspects of
the specification makes Java portable. Compiler in Java is written in ANSI C with a clean
portability boundary which is a POSIX subset.
Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly on
compile time error checking and runtime checking.
Multithreaded: With Java's multithreaded feature, it is possible to write programs that can
do many tasks simultaneously. This design feature allows developers to construct smoothly
running interactive applications.
Interpreted: Java byte code is translated on the fly to native machine instructions and is not
stored anywhere. The development process is more rapid and analytical since the linking is an
incremental and lightweight process.

High Performance: With the use of Just-In-Time compilers, Java enables high
performance.
Distributed: Java is designed for the distributed environment of the internet.
Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to
adapt to an evolving environment. Java programs can carry extensive amount of run-time
information that can be used to verify and resolve accesses to objects on run-time.

Tools you will need:


For performing the examples discussed in this tutorial, you will need a Pentium 200-MHz
computer with a minimum of 64 MB of RAM (128 MB of RAM recommended).
You also will need the following software:
Linux 7.1 or Windows 95/98/2000/XP operating system.
Java JDK 5
Microsoft Notepad or any other text editor

Java Environment Setup


Before we proceed further, it is important that we set up the Java environment correctly. This
section guides you on how to download and set up Java on your machine. Please follow the
following steps to set up the environment.
Java SE is freely available from the link Download Java. So you download a version based
on your operating system.
Follow the instructions to download Java and run the .exe to install Java on your machine.
Once you installed Java on your machine, you would need to set environment variables to
point to correct installation directories:
Setting up the path for windows 2000/XP:
Assuming you have installed Java in c:\Program Files\java\jdk directory:
Right-click on 'My Computer' and select 'Properties'.
Click on the 'Environment variables' button under the 'Advanced' tab.
Now, alter the 'Path' variable so that it also contains the path to the Java executable.
Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path
to read

'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.

Java Program structure :public class <Class Name>


{
public static void main(String arg[])
{
<Datatypes>;
.
<Set of codes>;
}
}

Example:- File Name- FirstJava.java


public class FirstJava
{
public static void main(String arg[])
{
System.out.println(This is my first java program);
}
}
Compile and execute the program:C:\>javac FirstJava.java
C:\>java FirstJava
This is my first java program
C:\>

Console input in Java :Java provides a package named IO which contains two important classes
named BufferedReader and InputStreamReader which is responsible
to accept input from standard input device I,e; keyboard.
In order to create object of these classes to read date from console input
iopackage must required to be explicitly import in the user program.

import java.io.*;

To accept input from standard input device follow the


following steps:Step1:-

At first create BufferedReaderobject in the following format.

BufferedReader
<object>=new
InputStreamReader(System.in));

BufferedReader(new

Step 2:- Read the data in the local variables using BufferedReader
method readLine() in the following format.
<Variable>=<BufferedReader Object>.readLine();
Note:- readLine() converts the data in to the String. String in java is an
object of class Strings

-: The Simple Data Types :Java defines eight simple (or elemental) types of data: byte, short, int, long, char, float,
double, and boolean. These can be put in four groups:
Integers: This group includes byte, short, int, and long, which are for whole valued signed
numbers.
Floating-point numbers: This group includes float and double, which represent numbers
with fractional precision.
Characters: This group includes char, which represents symbols in a character set, like
letters and numbers.
Boolean: This group includes boolean, which is a special type for representing true/false
values.

Integers
Java defines four integer types: byte, short, int, and long. All of these are signed,
positive and negative values. Java does not support unsigned, positive-only integers. Many
other computer languages, including C/C++, support both signed and unsigned integers.
However, Javas designers felt that unsigned integers were unnecessary. Specifically,
they felt that the concept of unsigned was used mostly to specify the behavior of the highorder bit, which defined the sign of an int when expressed as a number.
Name

Width

Range

Long

64

9,223,372,036,854,775,808

int

32

2,147,483,648

short

16

byte

to 9,223,372,036,854,775,807
to

2,147,483,647

32,768

to

32,767

128

to

127

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

Width in Bits

Approximate Range

Double

64

4.9e324 to 1.8e+308

float

32

1.4e045 to 3.4e+038

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
Here is a program that demonstrates char variables:

// Demonstrate char data type.


class CharDemo {
public static void main(String args[]) {
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}

This program displays the following output:


ch1 and ch2: X Y

Booleans
Java has a simple type, called boolean, for logical values. It can have only one of two
possible values, true or false. This is the type returned by all relational operators, such as a <
b. boolean is also the type required by the conditional expressions that govern the control
statements such as if and for.

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. In addition, all variables have
a scope, which defines their visibility, and a lifetime.

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. You can initialize the variable by specifying an equal sign and a value
to declare more than one variable of the specified type, use a comma-separated list.
Here are several examples of variable declarations of various types. Note that some include
an initialization.
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing
// d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.

-:Control Statement:Java supports three type of control statement for controlling the set of
statements. These are:
1. Selection Statement
2. Looping Statement
3. Jump Statement

1.Selection Statement :Java supports two type of selection statement, if and switch. These
statements allow controlling the flow of our programs execution based
upon conditions known only during run time.

if construct:-

(a)

The if decision construct is followed by a logical


expression in which data is compared and decision is made based on the
result of the comparison.

Syntax
if(<Boolean expression>)
{
<Set of Statements>;
}
else
{
<Set of statements>;
}
(b)

Nested if construct:-

A nested if is an if statement that is the target of


another if or else. Nested if is very common in programming.

Syntax
if(<Boolean expression>)
{
<Set of Statements>;
if(<Boolean expression>)
{
<Set of Statements>;
}
else
{
<Set of statements>;
}
}
else
{
<Set of statements>;
if(<Boolean expression>)
{
<Set of Statements>;
}
}
(c)

If-else-if construct:-

Java supports an else-if word. By using it we


will check the condition in option part of our conditional statement.

Syntax
if(<Boolean expression>)
{
<Set of Statements>;

else if(<Boolean expression>)


{
<Set of Statements>;
}
else if(<Boolean expression>)
{
<Set of statements>;
}
else
{
<Set of statements>;
}
(d)

Switch case:-

Switch case structure is used to execute sequence


of statements based on selection specified with case statements.

Syntax
switch (choice)
{
case 1:
<Set Of Statements>;
break;
case 2:
<Set Of Statements>;
break;
case 3:
<Set Of Statements>;
break;
default:

<Set Of Statements>;
}

Note: Only constraint numeric and character value are allowed with case
statements.
Variable or expression is allowed within the parenthesis of switch case.
Default is optional and can be used if required.
Break within switch can be used to break the control of execution and
continue on resume it just very next close curly braces encountered.
The switch case is internally working on numeric constant.
Maximum of 33 switch structure can be a target of another switch.
Example
import java.io.*;
public class SwitchCase
{
public static void main(String arg[])throws IOException
{
BufferedReader
obj=new
BuggeredReader(new
InputStreamReader(System.in));
int dno;
System.out.println(Enter day Number);
dno=Integer.valueOf(obj.readLine()).intValue();
switch(dno)
{
case 1:
System.out.println(SunDay);
break;
case 2:
System.out.println(MonDay);
break;
case 3:
System.out.println(TuesDay);
break;
case 4:
System.out.println(WedDay);
break;
..
case 7:
System.out.println(SaturDay);

10

break;
default :
System.out.println(Invalid Day Number);
break;
}
}
}

2.Looping Statement :-

A loop causes a section of a program to be repeated a certain number of


times. The repetition continues while the condition becomes false. The
loop ends and the control are passed to the statement following the loop.
Java support three looping constructs
While loop
Do while loop
For loop

While loop:The while statement continually executes a block of


statements while a particular condition is true. Its syntax can be
expressed as:

Syntax
while (expression)
{
<Set of statement(s)>;
< Increment /Decrement>;
}
NOTE:

The while statement evaluates expression, which must return a Boolean


value. If the expression evaluates to true, the while statement executes
the set of STATEMENT(s) in the while block. The while statement continues
testing the expression and executing its block until the expression
evaluates to false.

Increment/ Decrement statement is required to break the loop in certain


period.

If no Increment/ Decrement statement is found in the body of loop, the


loop becomes infinite.

11

DoWhile loop:In some conditions in java, you need to run some statements and
processes once at least. For that you have to use the do while loop in after
that check the condition then we use the do-while loop statement. dowhile loop is same as the while loop statement but while loop checks the
certain condition is first and if condition is true then statements or
processes are executed otherwise all the statements written under the
while loop is ignored by the interpreter but do - while loop executes all the
statements first at once and then check the condition if the condition is
true then all the statements are also executed in second times otherwise
second times ignored all the statements.

Syntax
do
{
<Set of statement(s)>;
< Increment /Decrement>;
}while(condition);
NOTE:

In a dowhile structure the condition is checked at the end /bottom so, if


very first time condition is false, the loop body executed at the last one
time.

The dowhile loop is basically used for menu driven programming.

The condition terminated by semicolon.

For loop:The for statement provides a compact way to iterate over a range of
values. Programmers often refer to it as the "for loop" because of the way in which it
repeatedly loops until a particular condition is satisfied.

Syntax
for (initialization; termination; increment)
{
<Set of statement(s)>;
}

NOTE:-

12

The initialization expression initializes the loop; it's executed once, as the loop begins.

When the termination expression evaluates to false, the loop terminates.

The increment expression is invoked after each iteration through the loop; it is
perfectly acceptable for this expression to increment or decrement a value.
Example
public class ForDemo
{
public static void main(String[] args)
{
for(int i=1; i<11; i++)
{
System.out.println("Count is: " + i);
}
}
}

3.Jump Statement :Java support four jump statements; break, continue, return an exit(). These
statements transfer control to another part of program.

Break:
The break statement is used in many programming languages such as c,
c++, java etc. Sometimes we need to exit from a loop before the
completion of the loop then we use break statement and exit from the loop
and loop is terminated. The break statement is used in while loop, do while loop, for loop and also used in the switch statement.
Break statement is used in java for jump the control very next close curly
braces. And execute continue the program.

Syntax
break;

13

Continue:
The continue statement is used in many programming languages such as
C, C++, java etc. Sometimes we do not need to execute some statements
under the loop then we use the continue statement that stops the normal
flow of the control and control returns to the loop without executing the
statements written after the continue statement. There is the difference
between break and continue statement that the break statement exit
control from the loop but continue statement keeps continuity in loop
without executing the statement written after the continue statement
according to the conditions.

Syntax
continue;

Return :
The return statement is used to explicitly return from a method. That is, it
causes program control to transfer back to the caller of the method. As
such, it is categorized as a jump statement. A brief look at return is
presented here.
At any time in a method the return statement can be used to cause
execution to branch back to the caller of the method. Thus, the return
statement immediately terminates the method in which it is executed.

Syntax
return;
or
return(var/const/expression);

exit() :
exit() is a control statement. Which is used to exit from JVM(Java Virtual
Machine). It is a method of System class of Java.lang package.

Syntax
System.exit(int const.);

14

15

Java Arrays
Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, .., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables. .
Declaring Array Variables:
To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can reference. Here is the syntax for declaring an array
variable:
dataType[ ] arrayRefVar;
Example: The following code snippets are examples of this syntax:
double[] myList;
Creating Arrays:
You can create an array by using the new operator with the following syntax:
arrayRefVar =new dataType[arraySize];
The above statement does two things:
It creates an array using new dataType[arraySize];
It assigns the reference of the newly created array to the variable arrayRefVar. Declaring
an array variable, creating an array, and assigning the reference of the array to the variable
can be combined in one statement, as shown below:
dataType[ ] arrayRefVar =new dataType[arraySize];
Alternatively you can create arrays as follows:
dataType[ ] arrayRefVar ={value0, value1,..., valuek};
The array elements are accessed through the index. Array indices are 0-based; that is, they
start from 0 to arrayRefVar.length-1.
Example:
Following statement declares an array variable, myList, creates an array of 10 elements of
double type and assigns its reference to myList:
double[ ] myList =new double[10];

16

-: Class & Object :Class:A class defines the behaviors of an object. A class is a user-defined
data type with a template that serves to define its properties. Once the
class type has been defined we can create variables of those types using
declarations that are similar to the basic type declarations. In java these
variables are termed as instances of classes which are the actual objects.
The basic form of a class definitionis:A class has data members (Attributes) and member functions
(methods). The data members and methods of a class body,in java braces
({ }) are marks the beginning and end of the methods or class. Braces are
also used to delimit blocks of object in loops and iterative statements.

Syntax for Declaring Class


class classname
{
type instance-variable1;
type instance-variable2;// ...
type instance-variableN;
type methodname1(parameter-list)
{
// body of method
}
type methodname2(parameter-list)
{
// body of method
THE JAVA LANG}
// ...
type methodnameN(parameter-list)
{
// body of method

17

}
}

Note:1) A class name is mandatory and must be given while declaring a class. The
class name is referred to the class and to create instance of the class.
2) The class keyword is used to create class.
3) The access specifier and modifier is optional and are covered later in this
section.

Object:An object is an instance of a class. Declaring an object is same as


declaring of variables. Define object type/user define type using reserve
key word class is simply a logical frame work with no reality.
To physically allocate object of user define type required two steps to
comes in to existence.

Step 1.
At first allocate object reference variable in the following format.

<Object
type/Class
name>Object_refference_variable1,
Object_refference_variable2,..;

At this step no object is physically created and the object


reference variable is by default inislized with NULL.

Step2.
Finally new operator must be used in the following format to
physically allocated the object of define type and return the reference to
the object reference variable.
Object_refference_variable = new <Object type/Class name>;

Note:These two steps combined in the single step as follows.

18

<Object type/Class name>


<Object type/Class name>;

Object_refference_variable=

new

-: Constructor:A constructor creates an Object of the class that it is in by initializing all


the instance variables and creating a place in memory to hold the Object.
It is always used with the keyword new and then the Class name. For
instance, new String(); constructs a new String object.
Sometimes in a few classes you may have to initialize a few of the
variables to values apart from their predefined data type specific values. If
java initializes variables it would default them to their variable type
specific values. For example you may want to initialize an integer variable
to 10 or 20 based on a certain condition, when your class is created. In
such a case you cannot hard code the value during variable declaration.
Such kind of code can be placed inside the constructor so that the
initialization would happen when the class is instantiated.

Example
public class Cube1
{
int length;
int breadth;
int height;
public int getVolume()
{
return (length * breadth * height);
}
Cube1()
{
length = 10;

19

breadth = 10;
height = 10;
}
Cube1(int l, int b, int h)
{
length = l;
breadth = b;
height = h;
}
public static void main(String[] args)
{
Cube1 cubeObj1, cubeObj2;
cubeObj1 = new Cube1();
cubeObj2 = new Cube1(10, 20, 30);
System.out.println(Volume
cubeObj1.getVolume());

of

Cube1

is

System.out.println(Volume
cubeObj2.getVolume());

of

Cube1

is

}
}

Rules for a constructor:1. A constructor has the same name as that of the class for which it is declare
since called automatically when an object is created.
2. A constructor does not have return type. As we do not call the constructor
explicitly. We can not use the return value anyway.
3. Basically java support two type of constructor. I,e:

Default constructor

Parameterized constructor

Differences between methods and constructors.

There is no return type given in a constructor signature (header). The


value is this object itself so there is no need to indicate a return value.

20

There is no return statement in the body of the constructor.

The first line of a constructor must either be a call on another constructor


in the same class (using this), or a call on the superclass constructor (using
super). If the first line is neither of these, the compiler automatically
inserts a call to the parameterless super class constructor.
These differences in syntax between a constructor and method are
sometimes hard to see when looking at the source. It would have been
better to have had a keyword to clearly mark constructors as some
languages do.

Default constructor
If you don't define a constructor for a class, a default
parameterless constructor is automatically created by the compiler. The
default constructor calls the default parent constructor (super()) and
initializes all instance variables to default value (zero for numeric types,
null for object references, and false for booleans).

Example
public class Cube1
{
int length;
int breadth;
int height;
public int getVolume()
{
return (length * breadth * height);
}
Cube1()
{
length = 10;
breadth = 10;
height = 10;
}

21

public static void main(String[] args)


{
Cube1 cubeObj1, cubeObj2;
cubeObj1 = new Cube1();
System.out.println(Volume
cubeObj1.getVolume());

of

Cube1

is

}
}

Parameterized constructor
At the time of creating object(instance) we will passed
the argument/parameter. In that condition the parameterized constructor
will be called for passing arguments.

Garbage collector:Objects are dynamically created with the help of new


operator. These all objects are created in memory and by default not
deallocated. In other programming languages like c++. These memory
areas will be deallocated with the help of delete operator. But in case of
java it takes different approach. It handles deallocation automatically. The
technique that accomplishes this is called garbage collection.

-:Inheritance:Inheritance is one of the main concepts of object oriented


programming. The base class is named superclass and the child class is
named subclass. Using inheritance we can achieve the concepts of
reusability. The child class can use the methods and variables of the
superclass and add to them its own methods and variables. Inheritance
represents problems in the real world.

Notes:1) Subclass can only inherit public and protected members but not private
members.

22

2) You can only inherit from single class. (Single inheritance).That is means
there is no multiple inheritance in Java. But as a solution to the multiple
inheritance java supported class types called interfaces.

Example
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();

23

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 ofits superclass. */
subOb.i = 7;
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();
}
}

What You Can Do in a Subclass


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

The inherited fields can be used directly, just like any other fields.

You can declare a field in the subclass with the same name as the one in
the superclass, thus hiding it (not recommended).

You can declare new fields in the subclass that are not in the superclass.

The inherited methods can be used directly as they are.

24

You can write a new instance method in the subclass that has the same
signature as the one in the superclass, thus overriding it.

You can write a new static method in the subclass that has the same
signature as the one in the superclass, thus hiding it.

You can declare new methods in the subclass that are not in the
superclass.

You can write a subclass constructor that invokes the constructor of the
superclass, either implicitly or by using the keyword super.

Private Members in a Superclass


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

Basically Java supports only two types of inheritance:


1) Single Inheritance
2) Multi Level Inheritance

1)

Single Inheritance:-

An inheritance in side which a single base class inherits a single derive


class is known as single inheritance.
When a subclass is derived simply from it's parent class then this
mechanism is known as simple inheritance. In case of simple inheritance

25

there is only a sub class and it's parent class. It is also called single
inheritance or one level inheritance.

Simple Inheritance

2)

Multilevel Inheritance:-

It is the enhancement of the concept of inheritance. When a subclass is


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

Multilevel Inheritance

Java does not support multiple Inheritance

Multiple Inheritances
The mechanism of inheriting the features of more than one base class into
a single class is known as multiple inheritances. Java does not support

26

multiple inheritances but the multiple inheritance can be achieved by


using the interface.

In Java Multiple Inheritance can be achieved through use of Interfaces by


implementing more than one interfaces in a class.

-: Package :A package is a grouping of related types providing access protection and


name space management. Note that types refer to classes, interfaces,
enumerations, and annotation types. Enumerations and annotation types
are special kinds of classes and interfaces, respectively, so types are often
referred to in this lesson simply as classes and interfaces.

Using Package Members


The types that comprise a package are known as the package members.
To use a public package member from outside its package, you must do one
of the following:

Refer to the member by its fully qualified name

Import the package member

Import the member's entire package

27

Each is appropriate for different situations, as explained in the sections


that follow.

IMPORTING A PACKAGE MEMBER


To import a specific member into the current file, put an import statement
at the beginning of the file before any type definitions but after the
package statement, if there is one. Here's how you would import the
Button class from the awt package.
import Java.awt.Button;

Now you can refer to the Button class by its simple name.
Buttonbtn1 = new Button (Button1);

This approach works well if you use just a few members from the awt
package. But if you use many types from a package, you should import the
entire package.

IMPORTING AN ENTIRE PACKAGE


To import all the types contained in a particular package, use the import
statement with the asterisk (*) wildcard character.
import java.awt.*;
Now you can refer to any class or interface in the awt package by its
simple name.
Buttonbtn1 = new Button (Button 1);
Label lbl1 = new Label(Label 1);

The asterisk in the import statement can be used only to specify all the
classes within a package, as shown here. It cannot be used to match a
subset of the classes in a package. For example, the following does not
match all the classes in the awt package that begin with A.
import awt.A*;

//DOES NOT WORK

Instead, it generates a compiler error. With the import statement, you


generally import only a single package member or an entire package.

28

For convenience, the Java compiler automatically imports three entire


packages for each source file: (1) the package with no name,
(2) the java.lang package
(3) the current package (the package for the current file)

APPARENT HIERARCHIES OF PACKAGES


At first, packages appear to be hierarchical, but they are not. For example,
the Java API includes a java.awt package, a java.awt.color package, a
java.awt.font package, and many others that begin with java.awt.
However, the java.awt.color package, the java.awt.font package, and other
java.awt.xxxx packages are not included in the java.awt package. The
prefix java.awt (the Java Abstract Window Toolkit) is used for a number of
related packages to make the relationship evident, but not to show
inclusion.
Importing java.awt.* imports all of the types in the java.awt package, but it
does not importjava.awt.color, java.awt.font, or any other java.awt.xxxx
packages. If you plan to use the classes and other types in java.awt.color
as well as those in java.awt, you must import both packages with all their
files:
import java.awt.*;
import java.awt.color.*;

Creating a Package
To create a package, you choose a name for the package and put a
package statement with that name at the top of every source file that
contains the types (classes and interfaces) that you want to include in the
package.
The package statement (for example, package graphics;) must be the first
line in the source file. There can be only one package statement in each
source file, and it applies to all types in the file.

Note: If you put multiple types in a single source file, only one can be
public, and it must have the same name as the source file. For example,
you can define public class Circle in the file Circle.java, define public
interface Draggable in the file Draggable.java, define public enum Day in
the file Day.java, and so forth.

29

You can include non-public types in the same file as a public type (this is
strongly discouraged, unless the non-public types are small and closely
related to the public type), but only the public type will be accessible from
outside of the package. All the top-level, non-public types will be package
private.

If you put the graphics interface and classes listed in the preceding section
in a package called graphics, you would need six source files, like this:

If you do not use a package statement, your type ends up in an


unnamed package. Generally speaking, an unnamed package is only for
small or temporary applications or when you are just beginning the
development process. Otherwise, classes and interfaces belong in named
packages.

AWT
The Abstract Window Toolkit (AWT) was introduced in Chapter 19 because
it provides support for applets. This chapter begins its in-depth
examination. The AWT contains numerous classes and methods that allow
you to create and manage windows. A full description of the AWT would
easily fill an entire book.
Therefore, it is not possible to describe in detail every method, instance
variable, or class contained in the AWT. However, this and the following
two chapters explain the techniques needed to effectively use the AWT
when creating your own applets or stand-alone programs. From there, you
will be able to explore other parts of the AWT on your own.
In this chapter, you will learn how to create and manage windows, manage
fonts, output text, and utilize graphics. Chapter 22 describes the various
controls, such as scroll bars and push buttons, supported by the AWT. It
also explains further aspects of Javas event-handling mechanism. Chapter
23 examines the AWTs imaging subsystem and animation.
Although the main purpose of the AWT is to support applet windows, it can
also be used to create stand-alone windows that run in a GUI environment,
such as Windows. Most of the examples are contained in applets, so to run
them, you need to use an applet viewer or a Java-compatible Web browser.

Class

Description

AWTEvent

Encapsulates AWT events.

AWTEventMulticaster

Dispatches events to multiple listeners.

BorderLayout
use five

The border layout manager. Border layouts

30

components

North, South, East, West, and Center.

Button

Creates a push button control.

Canvas

A blank, semantics-free window.

CardLayout
The card layout manager. Card layouts
emulate
index cards. Only the one on top is showing.
Checkbox

Creates a check box control.

CheckboxGroup

Creates a group of check box controls.

CheckboxMenuItem

Creates an on/off menu item.

Choice
Creates a pop-up list.
Color Manages colors in a portable, platform-independent
fashion.
Component
components.
Container
components.

An abstract superclass for various AWT


A subclass of Component that can hold other

Cursor

Encapsulates a bitmapped cursor.

Dialog

Creates a dialog window.

Dimension
Specifies the dimensions of an object. The
width is
stored in width, and the height is stored in height.
Event

Encapsulates events.

EventQueue

Queues events.

FileDialog
selected.

Creates a window from which a file can be

FlowLayout
The flow
positions
Components left to right, top to bottom.
Font
FontMetrics
font.

layout

manager.

Flow

layout

Encapsulates a type font.


Encapsulates various information related to a

31

This information helps you display text in a window.


Frame
bar, resize
corners, and a menu bar.

Creates a standard window that has a title

Graphics
Encapsulates the graphics context. This context is
used by the various output methods to display
output in a window.
GraphicsDevice
or printer.

Describes a graphics device such as a screen

SWINGS
Swing is a set of classes that provides more powerful and flexible
components than are possible with the AWT. In addition to the familiar
components, such as buttons, check boxes, and labels, Swing supplies
several exciting additions, including tabbed panes, scroll panes, trees, and
tables. Even familiar components such as buttons have more capabilities
in Swing. For example, a button may have both an image and a text string
associated with it. Also, the image can be changed as the state of the
button changes.
Unlike AWT components, Swing components are not implemented by
platform-specific code. Instead, they are written entirely in Java and,
therefore, are platform-independent. The term lightweight is used to
describe such elements. The number of classes and interfaces in the Swing
packages is substantial, and this
chapter provides an overview of just a few. Swing is an area that you will
want to explore further on your own. The Swing component classes that
are used in this book are shown here:
Class Description
AbstractButton -

Abstract superclass for Swing buttons.

ButtonGroup
buttons.

ImageIcon

- Encapsulates an icon.

JApplet
JButton
JCheckBox

Encapsulates a mutually exclusive set of

- The Swing version of Applet.


- The Swing push button class.
- The Swing check box class.

32

JComboBox

- Encapsulates a combo box (an combination of a

drop-down

- list and text field).

JLabel

- The Swing version of a label.

JRadioButton

JScrollPane

- Encapsulates a scrollable window.

JTabbedPane

Encapsulates a tabbed window.

JTable

Encapsulates a table-based control.

JTextField

- The Swing version of a text field.

JTree
DEVELOPMENT
USING JAVA

The Swing version of a radio button.

Encapsulates a tree-based control.SOFTWARE

JApplet

Fundamental to Swing is the JApplet class, which extends Applet. Applets


that use Swing must be subclasses of JApplet. JApplet is rich with
functionality that is not found in Applet. For example, JApplet supports
various panes, such as the content pane, the glass pane, and the root
pane. For the examples in this chapter, we will not be using most of
JApplets enhanced features. However, one difference between Applet
and JApplet is important to this discussion, because it is used by the
sample applets in this chapter. When adding a component to an instance
of JApplet, do not invoke the add( ) method of the applet. Instead, call
add( ) for the content pane of the JApplet object. The content pane can
be obtained via the method shown here:
Container getContentPane( )
The add( ) method of Container can be used to add a component to a
content pane.
Its form is shown here:
void add(comp)

Event-Driven Programs
Your actions when youre using the GUI for a window-based program or an
appletclicking a menu item or a button, moving the mouse, and so on
are first recognized by the operating system. For each action, the
operating system determines which of the programs currently running on

33

your computer should know about it and passes the action on to that
program. When you click a mouse button, its the operating system that
registers this and notes the position of the mouse cursor on the screen. It
then decides which application controls the window where the cursor was
when you pressed the button, and communicates the mouse button-press
to that program. The signals that a program receives from the operating
system as a result of your actions are called events. The basic idea of how
actions and events are communicated to your program code.
A program is not obliged to respond to any particular event. If you just
move the mouse, for example, the program need not invoke any code to
react to that. If it doesnt, the event is quietly disposed of. Each event that
the program does recognize is associated with one or more methods, and
when the event occurswhen you click a menu item, for examplethe
appropriate methods will be called automatically.
A window-based program is called an event-driven program because
the sequence of events created as a result of your interaction with the GUI
drives and determines what happens in the program.

Event

Class Description

ActionEvent
Generated when a button is pressed, a list item is
double-clicked, or a menu item is selected.
AdjustmentEvent

Generated when a scroll bar is manipulated.

ComponentEvent
resized,
or becomes visible.

Generated when a component is hidden, moved,

ContainerEvent
removed
from a container.

Generated when a component is added to or

FocusEvent
keyboard focus.

Generated when a component gains or loses

InputEvent
classes.

Abstract super class for all component input event

ItemEvent
Generated when a check box or list item is clicked;
also
occurs when a choice selection is made or a checkable
menu item is selected or deselected.
KeyEvent

Generated when input is received from the keyboard.

34

MouseEvent
Generated when the mouse is dragged, moved,
clicked,
pressed, or released; also generated when the mouse enters
or exits a component.
MouseWheelEvent
(Added by
Java 2, version 1.4)
TextEvent
changed.

Generated when the mouse wheel is moved.

Generated when the value of a text area or text field is

WindowEvent Generated when a


deactivated,
deiconified, iconified, opened, or quit.

35

window

is

activated,

closed,

Anda mungkin juga menyukai