Download File

Document related concepts
no text concepts found
Transcript
INTRODUCTION TO JAVA
The Java Programming language was first developed in 1990 by an engineer at Sun
Microsystems named James Gosling.
He was unhappy with the C++ programming language so he created a new language that
he called “Oak” after the Oak tree that he could see from his office window.
As the popularity of the World Wide Web grew, Sun recognized that Gosling’s language
could be developed to run applications on a web page.
The language was renamed “Java” simply because the name sounded good and was made
freely available by Sun in 1995.
Developers around the world quickly adopted this exciting new language, and because of
its modular design, began to create new features that could be added to the core language.
Many of these additional features were incorporated into Java when it was updated in
1998 and renamed “Java 2”.
Subsequent updates have enhanced some multimedia features and added support for the
Linux operating system.
The essence of Java is a library of files called “classes” that each contain small pieces of
ready-made proven code.
Any of these classes can be added into a new program, like bricks in a wall, so that a
relatively small amount of new code ever needs to be written. This saves the programmer
a vast amount of time and largely explains the huge popularity of Java programming.
Also this modular arrangement makes it much easier to identify any errors than would a
large single large program.
JAVA FEATURES
Expressivity
A language L is as expressive as another language M if and only if any expression in L
can be translated into an expression with the same meaning in M.
Portability
This is the ability to reuse a whole application from one environment to another without
any changes at all or simply by making small changes in absolute sense. This portability
is of both source code and compiled byte-code. E.g The same .class file can be run
anywhere. Write One Run Anywhere (WORA).
Portability leaves open the option to upgrade hardware, or to jump ship to some other
operating system if your current vendor misbehaves. It makes it easier to upgrade to
1
future versions of the current operating system. It leaves open the option to reuse or sell
your software to some other user with different hardware or operating system.
Modularity
A problem is decomposed into smaller and smaller sub-problems until each sub-problem
represents one logical task. Each logical task is implemented by a different module
(known as a method in Java), or a class
Cohesion and Coupling
Coupling is the strength of interaction between objects in system. It measures the
interdependence among modules.
Cohesion is the degree to which the tasks performed by a single module are
functionally related. It measures the logical relationship among the items that comprise
an object.
Generalization
A generalization is a taxonomic relationship between a more general element and a more
specific element. The more specific element is fully consistent with the more general
element (it has all of its properties, members, and relationships) and may contain
additional information.
Object-Oriented Programming
To learn about OOP, you need to understand three main concepts that are the backbone of
OOP. These concepts, which are covered in the following sections, are: encapsulation,
inheritance, and polymorphism.
Encapsulation
Encapsulation enables you to hide, inside the object, both the data fields and the
methods that act on that data. (In fact, data fields and methods are the two main
elements of an object in the Java programming language.) After you do this, you can
control access to the data, forcing programs to retrieve or modify data only through the
object's interface. In strict object-oriented design, an object's data is always private to
the object. Other parts of a program should never have direct access to that data.
Inheritance
Inheritance enables you to create a class that is similar to a previously defined class,
but one that still has some of its own properties. Consider a car-simulation program.
Suppose that you have a class for a regular car, but now you want to create a car that has
a high-speed passing gear.
To use the object-oriented approach: Create a new class by inheritance. This new class
inherits all the data and methods from the tested base class. (You can control the level of
inheritance with the public, private, and protected keywords.
Polymorphism
The last major feature of object-oriented programming is polymorphism. By using
polymorphism, you can create new objects that perform the same functions as the
base object but which perform one or more of these functions in a different way. For
example, you may have a shape object that draws a circle on the screen. By using
2
polymorphism, you can create a shape object that draws a rectangle instead. You do this
by creating a new version of the method that draws the shape on the screen. Both the old
circle-drawing and the new rectangle-drawing method have the same name (such as
DrawShape()) but accomplish the drawing in a different way.
Classes as Data Types
An object is just an instance of a data type. For example, when you declare a variable
of type int, you're creating an instance of the int data type.
A class is like a data type in that it is the blueprint upon which an object is based. When
you need a new object in a program, you create a class, which is a kind of template for
the object. Then, in your program, you create an instance of the class. This instance is
called an object.
Classes are really nothing more than user-defined data types. As with any data type, you
can have as many instances of the class as you want. For example, you can have more
than one window in a Windows application, each with its own contents.
For example, think again about the integer data type (int). It's absurd to think that a
program can have only one integer. You can declare many integers, just about all you
want. The same is true of classes. After you define a new class, you can create many
instances of the class. Each instance (called an object) normally has full access to the
class's methods and gets its own copy of the data members.
FIRST JAVA PROGAM
All Java programs start as text files that are later used to create “class” files which are
actual runnable programs.
This means that Java programs can be written in any simple text editor such as Windows
Notepad application.
The Java code that is entered below will generate the output “Welcome to Java”
public class Welcome
{
public static void main(String[ ] args)
{
System.out.println(“Welcome to Java”);
}
}
Programs are Java classes and the first line of this code defines the name of this program
as “Welcome”.
It is important to note that Java is a case sensitive language where “Welcome” and
“welcome” are two different programs.
3
Java programs files are saved with their exact program name, matching character case,
and with the extension “.java”.
So the above program is saved as a file named “Welcome.java”.
The Welcome program analysed
The above program can be broken down in three different parts to understand it more
clearly.

The Program Container
public class Welcome{ }
The program name is declared following the “public class” keywords and followed by
a pair of curly brackets.
All of the program code that defines the Welcome class will be contained within these
curly brackets.

The Main method
public static void main(String[ ] args)
This line is used to define the starting point of nearly all Java programs. This code is used
almost throughout all programs, so it may be usefully memorized.
The code declares a method named “main” that will contain the actual program
instructions within its curly brackets.
Keywords “public static void” prefix the method name to define how it may be used and
will be explained later.
The code “String[] args) is useful when passing values to the method and is also
explained later.

The Statement
System.out.println(“Welcome”);
Statements are actual instructions to perform program tasks and must always end with a
semi colon.
A method may contain many statements inside its curly brackets to form a statement
“block” but here a single statement instructs the program to output a line of text.
Compiling the Welcome program
Before a java program can run, it must first be compiled into a “class” file by the Java
compiler that is located in the Java directory bin folder and is an application named
“javac.exe”
4
At a command prompt, type javac then hit the <ENTER> key in order to reveal the javac
compiler options.
To compile a program at a command prompt type javac followed by a space then the path
and file name of the file to be compiled, for instance:
javac c:\MyJava\Welcome.java
Alternatively, change the prompt location to the directory containing the source file. Then
type javac followed by a space then the full name of the file to compile, for instance:
javac Welcome.java
If the compiler finds errors in the code it will halt and display a helpful error report
indicating the nature of the error.
Typically errors are due to incorrect source code syntax or where the compiler cannot
find the source file, due to an incorrectly entered file name or path.
If the compiler does not find errors it will create a new file with the program name and
with the file extension “.class”.
Running the Welcome Program
When the Java compiler completes compilation of a program source file program focus
returns a standard command prompt without confirming that the compilation was
successful.
Now the actual program can finally be run.
The SDK tool used to run Java programs is an application called “java.exe” located in the
Java directory bin folder.
At a command prompt simply type java then press the <ENTER> key in order to reveal
the java interpreter options.
To run a program at a command prompt type java followed by a space then the path and
file name of the program for instance:
javac c:\MyJava\Welcome
Alternatively, change the prompt location to the directory containing the class file. Then
type java followed by a space then the program name only.
java Welcome
When a program runs, the Java interpreter reads the program class file and executes its
instructions. In this case the statement contained in the program’s main method will
output the line of text “Welcome to Java”.
5
After the program has completed executing the program instructions, focus returns to
standard command prompt.
Integrated Development Developments (IDE)
The continual switching between text editor and command line when creating Java
programs can become tedious.
An integrated development environment is a piece of software that makes the process
more convenient.
There are many IDEs available for Java but all provide a built-in text editor, in which to
write the code and a graphical means to compile and run the code. This not only makes
life more pleasant but speeds development time and avoids the use of command lines.
Most IDE editors offer syntax highlighting that will apply different colours to each piece
of the program code to denote its relevance. For instance all keywords that are recognized
as part of the Java language might be bright red.
Another benefit offered by IDEs is an integrated debugger that can help to find any errors
in the program code.
Several Java IDEs are visual development tools that can very quickly build a program
interface by allowing components to be dragged into a base window. The IDE
environment will then automatically generate the appropriate code to add that component
to the program.
Popular Java Visual IDEs include:
 Jbuilder
 Visual Café
 JCreator
JPadPro is an example of a non-visual IDE application.
Comments and BackSlash
It is useful and good practice when writing Java code to add comments that describe what
each piece of code is doing.
This makes the code easier to understand when it is revisited after several months or
when it is viewed by someone else.
The Java compiler sees any text between the // and end of that line as a single –line
comment which it ignores. Also any text, on one or more lines, between /* and */ is also
ignored.
Spaces, tabs and new lines in the code are collectively known as “whitespace”. This too
is ignored by the compiler so code may be formatted and indented to make it more
readable.
6
The backslash character has a special meaning in strings. Inside quoted text strings \n will
force a line-break in the output and \t will add a tab spacing to the output. It is also useful
as \” will allow quotation marks to be used inside strings without prematurely terminating
the string.
These features are added to the Welcome program.
/* A First Java program – with added features*/
public class Welcome
{
public static void main(String[ ] args)
{
// Add a new line, a tab and quotation marks
System.out.println(“Welcome to Java”);
}
}
Classes and Objects
Classes
The most important thing about a class is that it defines a new data type. Once defined,
this new type can be used to create objects of that type.
Classes are made up of many different parts, such as methods and variables. The class is
a template for information about a group of things, even though the individual things may
be somewhat different.
A superclass is the top-level class of every application. In Java, it is automatically the
Object class. This means that if a class does not implicitly declare its superclass, or next
higher class level, then it is a subclass of Object.
Subclasses extend the superclass and create a new variation of the class. They inherit the
characteristics of the preceding class.
Defining a Class
Since a class is sort of a template for an object, it is equivalent to a data type such as int.
The main difference is that Java already knows what an integer is. However, when you
create a class, you must tell Java about the class's characteristics. You define a class by
using the class keyword along with the class name, like this:
class MyClass
{
}
The name associated with a class has the same restrictions that variable names do; that is,
they can be named anything as long as they begin with an alphabetic character, a dollar
sign, or an underscore. By convention, however, a class name should begin with a capital
letter. This makes the class easily distinguishable from methods, variables, and so on.
Java itself follows this convention; it is highly recommended.
7
Class Modifiers alter certain aspects of classes. They are specified in the declaration of a
class before the class name. Class modifiers are used to specify two aspects of classes:
access and type. Access modifiers are used to regulate internal and external use of
classes. Type modifiers declare the implementation of a class. A class can be used as
either a template for subclasses or a class in and of itself.
A Public class can be accessed outside their package by using the public statement in the
class declaration. If no explicit statement is made at declaration time, the class may be
accessed only from within its own package. A compile error is generated if any other
security modifier is used in the declaration, such as private or protected, which are
reserved for methods.
For example,
public class classname { //able to be accessed outside of
//own package
}
class classname {
//only able to be accessed within
//own package
}
Class Variables and Instance Variables
Class Variables and Instance Variables are declared outside a method definition.
Customarily, they are defined just after the first line of the class definition.
Class variables are variables that are defined and stored in the class itself. Their values,
therefore, apply to the class and to all its instances.
With instance variables, each new instance of the class gets a new copy of the instance
variables that class defines. Each instance can then change the values of those instance
variables without affecting any other instances. With class variables, there is only one
copy of that variable. Every instance of the class has access to that variable, but there is
only one value. Changing the value of that variable changes it for all the instances of that
class.
You define class variables by including the static keyword before the variable itself. For
example, take the following partial class definition:
class FamilyMember {
static String surname = "Johnson";
String name;
int age;
...
}
Instances of the class FamilyMember each have their own values for name and age. But
the class variable surname has only one value for all family members. Change surname,
and all the instances of FamilyMember are affected.
Access Modifiers
8
You can change the rules of access by using the public, protected, and private
keywords. A public variable can be accessed by any part of a program, inside or outside
of the class in which it's defined. A protected variable can only be accessed from within
the class or from within a derived class (a subclass). A private variable cannot even be
accessed by a derived class.
Class Methods
A method definition has four basic parts:
 The name of the method
 The type of object or primitive type the method returns
 A list of parameters
 The body of the method
The method's signature is a combination of the name of the method, the type of object or
base type this method returns, and a list of parameters.
Here's what a basic method definition looks like:
Modifier returntype methodname(type1 arg1, type2 arg2, type3 arg3..) {
...
}
Return Types
The returntype is the primitive type or class of the value this method returns. It can be
one of the primitive types, a class name, or void if the method does not return a value at
all. The return type immediately precedes the variable name of a method. The following
code declares a method named isBlack to return a variable with type boolean:
boolean isBlack (Color color) {
if (color == black)
return (true);
else
return (false);
}
The method body tests whether the color passed is black. If it is, the method uses the
return keyword to specify that value to return to the calling method is boolean true.
Otherwise, it will use return to return the boolean false.
NB: return keyword is used if a method returns any value.
void is a special return type in Java that indicates that there is no return type of any kind.
This is used for methods that have no need to return anything to the calling program, or
that modify only method arguments or global variables.
Note that if this method returns an array object, the array brackets can go either after the
return type or after the parameter list; because the former way is considerably easier to
read.
int[] makeRange(int lower, int upper) {...}
9
The method's parameter list is a set of variable declarations, separated by commas,
inside parentheses. These parameters become local variables in the body of the method,
whose values are the objects or values of primitives passed in when the method is called.
Inside the body of the method you can have statements, expressions, method calls to
other objects, conditionals, loops, and so on.
Method Modifiers
The concept of modifiers presented with classes also can be applied to methods. Method
modifiers control access to a method. Modifiers also are used to declare a method's type.
However, methods have more modifiers available than do classes.
In Java terms, accessibility is security. The five levels of access follow:
Access modifiers
Level
public
private
protected
private protected
<default>
Allowable Access
All other classes
No other classes
Subclasses or same package
Subclasses only
Same package
public
This modifier allows a method to be called by any class inside or outside the package.
private
The private modifier specifies that no classes, including subclasses, can call this method.
This can be used to completely hide a method from all other classes. If no other classes
can access the method, it can be changed as needed without causing problems. Here is an
example of a method declared private:
private void isBlack (Color color) {
....
}
protected
The protected modifier specifies that only the class in which the method is defined or
subclasses of that class can call the method. This allows access for objects that are part of
the same application, but not other applications. Here is an example:
protected void isBlack (Color color) {
....
}
private protected
The private protected modifier is a special combination of private and protected access
modifiers. This modifier specifies that only the class in which the method is defined or
subclasses of the class can call the method. It does not allow package access as
protected does but also allows subclasses as private does not. Here is an example:
private protected void isBlack (Color color) {
.....
}
10
default
The method defaults to an access control in which the class itself, subclasses, and classes
in the same package can call the method. In this case, no access type is explicit in the
method-declaration statement. Here is an example:
void isBlack (Color color) {
....
}
static
The static modifier is associated only with methods and variables, not classes. The
static modifier is used to specify a method that can only be declared once. No subclasses
are allowed to implement a method of the same name. This is used for methods, such
as main, that are entry points into a program. The operating system would not know
which method to call first if there were two main methods. Static methods are used to
specify methods that should not be overridden in subclasses. Here's an example:
static void isBlack (Color color) {
....
}
final
The final modifier indicates that an object is fixed and cannot be changed. When you use
this modifier with a class-level object, it means that the class can never have subclasses.
When you apply this modifier to a method, the method can never be overridden. When
you apply this modifier to a variable, the value of the variable remains constant. You
will get a compile-time error if you try to override a final method or class. You will also
get a compile-time error if you try to change the value of a final variable.
Here is how you can use the final modifier:
class neverChanging {
final int unchangingValue = 21; // a final variable
// a final method
final int unchangingMethod(int a, int b) {
}
}
abstract
The abstract modifier is used to create template methods. Abstract methods define return
type, name, and arguments but do not include any method body. Subclasses are then
required to implement the abstract method and supply a body. Here is an example of an
abstract class:
abstract void isBlack (Color color) {
}
This defines a template for a method named isBlack. Notice that no body of isBlack is
specified; that is left to subclasses of the class in which the abstract method is declared.
The subclasses must implement a body for method isBlack, or they will cause a compiletime error.
Working with Objects
Data space is not pre-allocated in Java. Instead, it is created as needed. Space is used for
as long as something is accessing the data, and then memory is automatically deallocated.
In Java, an automatic garbage-collection system finds any memory that is not in use and
11
automatically frees it. This is a huge bonus for the programmer because "memory leaks"
are a source of considerable problems in standard languages.
Creating an Instance
new creates an object of virtually any type, the exceptions being primitive data types. A
variable is then assigned that points to that object. An example of this follows:
String desc;
desc = new String(10);
This allocates enough space in memory for a 10-character string and associates it with the
variable desc. desc is now considered an object of type String and has all the methods
associated with class String. String methods include methods to determine length,
compare with other strings, obtain substrings, and many others.
In Java, the object associated with the variable desc already has all the methods built into
it. This is a result of the methods associated with type String. These methods became a
part of object desc when it was created with new, as in the following example:
sizeOfString = desc.length
//gets the size of desc
if (desc.compareTo("black")
//tests to see if desc is equal to "black"
locOfSubString = desc.indexOf("black"); // returns index to substring
These examples focus on the object, not the functions; thus the name object-oriented
programming.
Getting Values
To get to the value of an instance variable, you use dot notation. With dot notation, an
instance or class variable name has two parts: the object on the left side of the dot, and
the variable on the right side of the dot.
For example, if you have an object assigned to the variable myObject, and that object has
a variable called var, you refer to that variable's value like this:
myObject.var;
This form for accessing variables is an expression (it returns a value), and both sides of
the dot are also expressions. This means that you can nest instance variable access. If that
var instance variable itself holds an object, and that object has its own instance variable
called state, you can refer to it like this:
myObject.var.state;
Dot expressions are evaluated left to right, so you start with myObject's variable var,
which points to another object with the variable state. You end up with the value of that
state variable.
Changing Values
Assigning a value to that variable is equally easy—just tack an assignment operator on
the right side of the expression:
myObject.var.state = true;
Calling methods
12
Calling a method in objects is similar to referring to its instance variables: method calls
also use dot notation. The object whose method you're calling is on the left side of the
dot; the name of the method and its arguments is on the right side of the dot:
myObject.methodOne(arg1, arg2, arg3);
Note that all methods must have parentheses after them, even if that method takes no
arguments:
myObject.methodNoArgs();
If the method you've called results in an object that itself has methods, you can nest
methods as you would variables:
myObject.getClass().getName();
You can combine nested method calls and instance variable references as well:
myObject.var.methodTwo(arg1, arg2);
System.out.println(), the method you've been using all through the book this far, is a great
example of nesting variables and methods. The System class (part of the java.lang
package) describes system-specific behavior. System.out is a class variable that contains
an instance of the class PrintStream that points to the standard output of the system.
PrintStream instances have a println() method that prints a string to that output stream.
13
Class Example
The following class defines three variables and one method called volume:
class Box{
double width;
double height;
double depth;
//volume method
public void volume(){
System.out.println("Volume is " + width*height*depth);
}
}
To use the above class, we must create an object of its type. The following class does that
and then uses the class variables and the method defined in the class.
class BoxDemo{
public static void main(String[] args){
Box myBox=new Box();
//assign values
myBox.width=10; //call the variables
myBox.height=20;
myBox.depth=15;
//display volume
myBox.volume(); //call the method
}
}
The class could also be written using a method that returns a double value, as follows
class Box{
double width;
double height;
double depth;
//volume method
public double volume(){
return width*height*depth;
}
}
NB: the calling of the method volume changes. It is assigned to a variablebecause it
returns a value. This is shown in the following class:
class BoxDemo{
public static void main(String[] args){
Box myBox=new Box();
double vol;
//assign values
myBox.width=10;
myBox.height=20;
14
myBox.depth=15;
//display volume
vol = myBox.volume();
System.out.println("Volume is "+ vol);
}
}
Methods with parameters
A method defined with a list of parameters is also called using the same list of values
(arguments). Parameters in a method definition are called formal parameters or dummy
parameters. The parameters that are passed to a method when it is called (used) are
called actual parameters. When a method is called, the actual parameters in the method
call statement are evaluated and the values are assigned to the formal parameters in the
method's definition
For example, the following application defines a class with a method called square which
has one parameter.
class SquareDemo{
double square(double i){
return i*i;
}
}
class Calculate{
public static void main(String[] args){
SquareDemo obj=new SquareDemo();
System.out.println(obj.square(2.0))
}
}
Overloading Methods
This is defining a method with the same name, but with different and unique parameter
lists. Java selects which method of the same name to call on the basis of the calling
parameters. With Java you can overload any method in the current class or any superclass
unless the method is declared static. For example, in the following code, method test has
been overloaded four times:
class Overload {
void test() {
System.out.println(“No parameters”);
}
void test(int a) {
System.out.println(“a: ”+a);
}
void test(int a, int b) {
System.out.println(“a and b : ”+a + “ ” + b);
}
15
double test(double a) {
System.out.println(“double a: ”+a);
return a*a;
}
}
Class OverloadDemo{
Public class static void main(String[] args){
Overload ob=new Overload();
double result;
//call all versions of test
ob.test;
ob.test(10);
ob.test(10,20);
result=ob.test(123.2);
System.out.println(“Result of ob.tes(123.2): ”+result);
}
}
Creating Subclasses
To create a subclass of another class, use extends to indicate the superclass of this class:
class myClassName extends mySuperClassName {
...
}
Overriding Methods
When you call a method on an object, Java looks for that method definition in the class of
that object, and if it doesn't find one, it passes the method call up the class hierarchy until
a method definition is found. Method inheritance enables you to define and use methods
repeatedly in subclasses without having to duplicate the code itself.
However, there may be times when you want an object to respond to the same methods
but have different behavior when that method is called. In this case, you can override that
method.
Overriding a method involves defining a method in a subclass that has the same
signature as a method in a superclass. Then, when that method is called, the method in
the subclass is found and executed instead of the one in the superclass.
To override a method, all you have to do is create a method in your subclass that has the
same signature (name, return type, and parameter list) as a method defined by one of your
class's superclasses. Because Java executes the first method definition it finds that
matches the signature, this effectively "hides" the original method definition. The
following code shows a simple class with a method called printMe(), which prints out the
name of the class and the values of its instance variables.
16
//Method overriding
Class MySuper
{
void test()
{
System.out.println(“Superclass test method”);
}
}
Class MySub extends MySuper
{
void test()
{
System.out.println(“Subclass test method”);
}
}
The following class can call either the superclass or the subclass methods
Class OverrideDemo{
public class static void main(String[] args)
{
MySuper supObj=new MySuper();
MySub subObj=new MySub();
supObj.test();
subObj.test();
}
}
The super keyword
super is a reference to the superclass. It is often used as a shortcut or explicit way to
reference a member in the superclass of the current class. In the following code, a
subclass named MySub uses the super keyword to reference the method test in the
superclass MySuper:
//Method overriding
Class MySuper{
void test(){
System.out.println(“Superclass test method”);
}
}
Class MySub extends MySuper{
void test(){
System.out.println(“Subclass test method”);
17
Super.test(); //this calls the superclass’ test method
}
}
Abstract Classes and Methods
An abstract class defines a superclass that the structure of a given abstraction without
providing the complete implementation of every method. The abstract modifier is used to
create template classes. An abstract class can contain such things as variable declarations
and methods but cannot contain code for creating new instances, that is, it cannot be
instantiated.
An abstract class can contain both concrete and abstract methods. Abstract methods do
not include any method body. Subclasses are then required to implement those abstract
methods in which they supply a body. The following is an example:
//A simple abstract class
abstract class MySuper
{
//abstract method
abstract void callme();
//concrete method
Void callmetoo()
{
System.out.println(“Concrete method”);
}
}
class MySub extends MySuper
{
void callme()
{
System.out.println(“Subclass implementation of call me”);
}
}
class AbstractDemo{
public class static void main(String[] args)
{
MySuper superObj = new MySuper();
superObj.callme();
superObj.callmetoo();
System.out.println(“Subclass implementation of call me”);
}
}
18
VARIABLES AND DATA TYPES, ARRAYS AND DATA
OPERATORS
Variables
Variables are locations in memory in which values can be stored. They have a name, a
type, and a value. Before you can use a variable, you have to declare it. After it is
declared, you can then assign values to it.
Java actually has three kinds of variables: instance variables, class variables, and local
variables.
Instance variables are used to define attributes or the state for a particular object.
Class variables are similar to instance variables, except their values apply to all that
class’s instances (and to the class itself) rather than having different values for each
object.
Local variables are declared and used inside method definitions, for example, for index
counters in loops, as temporary variables, or to hold values that you need only inside the
method definition itself. They can also be used inside blocks ({ }). Once the method (or
block) finishes executing, the variable definition and its value cease to exist.
Use local variables to store information needed by a single method and instance
variables to store information needed by multiple methods in the object.
Although all three kinds of variables are declared in much the same ways, class and
instance variables are accessed and assigned in slightly different ways from local
variables.
Note: Unlike other languages, Java does not have global variables—that is, variables that
are global to all parts of a program. Instance and class variables can be used to
communicate global information between and among objects.
Declaring Variables
To use any variable in a Java program, you must first declare it. Variable declarations
consist of a type and a variable name, examples:
int myAge;
String myName;
boolean isTired;
Variable definitions can go anywhere in a method definition (that is, anywhere a regular
Java statement can go), although they are most commonly declared at the beginning of
the definition before they are used:
public static void main (String args[]) {
int count;
String title;
19
boolean isAsleep;
...
}
You can string together variable names with the same type:
int x, y, z;
String firstName, LastName;
You can also give each variable an initial value when you declare it:
int myAge, mySize, numShoes = 28;
String myName = “Laura”;
boolean isTired = true;
int a = 4, b = 5, c = 6;
If there are multiple variables on the same line with only one initializer (as in the first of
the previous examples), the initial value applies to only the last variable in a declaration.
You can also group individual variables and initializers on the same line using commas,
as with the last example, above.
Local variables must be given values before they can be used (your Java program will not
compile if you try to use an unassigned local variable). For this reason, it’s a good idea
always to give local variables initial values. Instance and class variable definitions do not
have this restriction (their initial value depends on the type of the variable: null for
instances of classes, 0 for numeric variables, ‘\0’ for characters, and false for booleans).
Notes on Variable Names
 Variable names in Java can start with a letter, an underscore (_), or a dollar sign ($).
They cannot start with a number. After the first character, your variable names can
include any letter or number.
 Symbols, such as %, *, @, and so on, are often reserved for operators in Java, so be
careful when using symbols in variable names.
 By convention, Java variables have meaningful names, often made up of several
words combined. The first word is lowercase, but all following words have an initial
uppercase letter:
Button theButton;
long reallyBigNumber;
boolean currentWeatherStateOfPlanetXShortVersion;
Variable Types
In addition to the variable name, each variable declaration must have a type, which
defines what values that variable can hold. The variable type can be one of three things:
1. One of the eight basic primitive data types
2. The name of a class
3. An array
20
The eight primitive data types handle common types for integers, floating-point numbers,
characters, and boolean values (true or false). They’re called primitive because they’re
built into the system and are not actual objects, which makes them more efficient to use.
Note that these data types are machine-independent, which means that you can rely on
their sizes and characteristics to be consistent across your Java programs.
Integer types
There are four integer types each with different ranges of values (as listed in the
following table). All are signed, which means they can hold either positive or negative
numbers. Which type you choose for your variables depends on the range of values you
expect that variable to hold; if a value becomes too big for the variable type, it is
truncated.
3
Type Size Range
byte 8 bits –128 to 127
Short 16 bits –-32,768 to 32,767
int
32 bits –2,147,483,648 to 2,147,483,647
long 64 bits –9223372036854775808 to 9223372036854775807
Floating types
Floating-point numbers are used for numbers with a decimal part. There are two floatingpoint types: float (32 bits, single-precision) and double (64 bits, double-precision).
Char type
The char type is used for individual characters. Because Java uses the Unicode character
set, the char type has 16 bits of precision, unsigned.
Boolean type
Finally, the boolean type can have one of two values, true or false. All tests of boolean
variables should test for true or false.
In addition to the eight basic data types, variables in Java can also be declared to hold an
instance of a particular class:
String LastName;
Font basicFont;
OvalShape myOval;
Each of these variables can then hold only instances of the given class. As you create new
classes, you can declare variables to hold instances of those classes (and their subclasses)
as well.
Assigning Values to Variables
Once a variable has been declared, you can assign a value to that variable by using the
assignment operator =:
size = 14;
tooMuchCaffiene = true;
21
Literals
Literals are used to indicate simple values in your Java programs. Literal is a
programming language term, which essentially means that what you type is what you get.
For example, if you type 4 in a Java program, you automatically get an integer with the
value 4. If you type ‘a’, you get a character with the value a.
Literals may seem intuitive most of the time, but there are some special cases of literals
in Java for different kinds of numbers, characters, strings, and boolean values.
Number Literals
There are several integer literals. 4, for example, is a decimal integer literal of type int
(although you can assign it to a variable of type byte or short because it’s small enough to
fit into those types).
 A decimal integer literal larger than an int is automatically of type long. You also
can force a smaller number to a long by appending an L or l to that number (for
example, 4L is a long integer of value 4).
 Negative integers are preceded by a minus sign—for example, -45.
 Integers can also be expressed as octal or hexadecimal: a leading 0 indicates that a
number is octal—for example, 0777 or 0004.
 A leading 0x (or 0X) means that it is in hex (0xFF, 0XAF45). Hexadecimal
numbers can contain regular digits (0–9) or upper- or lowercase hex digits (a–f or
A–F).
 Floating-point literals usually have two parts: the integer part and the decimal
part—for example, 5.677777. Floating-point literals result in a floating-point
number of type double, regardless of the precision of that number.
 You can force the number to the type float by appending the letter f (or F) to that
number—for example, 2.56F.
 You can use exponents in floating-point literals using the letter e or E followed by
the exponent (which can be a negative number): 10e45 or .36E-2.
Boolean Literals
Boolean literals consist of the keywords true and false. These keywords can be used
anywhere you need a test or as the only possible values for boolean variables.
Character Literals
Character literals are expressed by a single character surrounded by single quotes: ’a’,
’#’, ’3’, and so on. Character variables can also be assigned integer values. The variable
below (ch1) is assigned to integer 88 (equivalent of letter X):
Int ch1=88;
This allows addition of two characters together.
Escape Sequences
They allow nonprintable characters to be represented in the java programs. The table
below shows the escape sequences:
Escape
\n
\t
Meaning
Newline
Tab
22
\b
Backspace
\r
Carriage return
\f
Formfeed
\\
Backslash
\’
Single quote
\”
Double quote
\ddd
Octal
\xdd
Hexadecimal
\udddd Unicode character
If, for example, you want display a string output enclosed in double qotes, you would use
the double quote escape sequences as shown below:
System.out.println(“\”Welcome to Java Programming\””);
String Literals
A combination of characters is a string. Strings in Java are instances of the class String.
Because string objects are real objects in Java, they have methods that enable you to
combine, test, and modify strings very easily. String literals consist of a series of
characters inside double quotes:
“Hi, I’m a string literal.”
“” //an empty string
Strings can contain the escape sequences used by the character type such as newline, tab,
etc as shown below:
“A string with a \t tab in it”
“Nested strings are \”strings inside of\” other strings”
“This string brought to you by Java\u2122”
In the last example, the Unicode code sequence for \u2122 produces a trademark symbol
(™).
Note: Just because you can represent a character using a Unicode escape does not mean
your computer can display that character—the computer or operating system you are
running may not support Unicode, or the font you’re using may not have a glyph (picture)
for that character. All that Unicode escapes in Java provide is a way to encode special
characters for systems that support Unicode.
When you use a string literal in your Java program, Java automatically creates an
instance of the class String for you with the value you give it. Strings are unusual in this
respect; the other literals do not behave in this way (none of the primitive base types are
actual objects), and usually creating a new object involves explicitly creating a new
instance of a class.
Constants
Variables are marked as constants using the final keyword. For example,
final int monthsInYear=12;
23
The value 12 in monthsInYear cannot be changed.
Variable Scopes
If you declare a variable inside any method, the variable has a local scope. This means
that it's visible only for the code within this method. When the method is finished, the
variable automatically gets destroyed. If a variable has to be visible through more than
one method in a class, you should declare it on a class level. These variables are "alive"
when the class exists in memory. They could be shared and reused by all methods within
the class and they can even be visible from external classes.
A block creates a new local scope. Local variables can be declared inside a block, and
those variables will cease to exist after the block is finished executing. For example,
here's a block inside a method definition that declares a new variable y. You cannot use y
outside the block in which it's declared:
void testblock() {
int x = 10;
{ // start of block
int y = 50;
System.out.println("inside the block:");
System.out.println("x:" + x);
System.out.println("y:" + y);
} // end of block
y=30; //error occurs – y not known
}
NB: A variable cannot be declared in an inner scope with a similar name as the outer
scope.
Type conversion
It is possible to assign a value of one type to a variable of another type. For example it is
possible to assign an int value to a long variable. There are two ways of type conversion:
1. Implicit conversion
For this conversion to be possible the two types must be compatible and the destination
type must be larger than the source type. Numerical types are not compatible with char or
boolean. Also char and boolean are nor compatible with each other. The following
conversions are possible:
 byte to short, int, long, float or double
 short to int, long, float or double
 int to long, float or double
 long to float or double
 float to double
This is known as Widening Primitive conversion.
2. Type casting (explicit)
24
This conversion is done on incompatible types. For example, converting from int to byte
is not automatic because byte is smaller than int. This is known as Narrowing
conversion or type casting. The following example casts an int to a byte.
int a;
byte b;
b=(byte)a;
NB:
1. If an integer number is greater than the range of the destination type, it is
converted to a modulo (remainder after division).
2. Floating point numbers when assigned to integers are truncated (fraction lost)
Automatic type promotion
In an expression, an immediate value may exceed the range of either operand. For
example:
byte a=40, b=50, c=100;
int d=a*b*c;
Java automatically promotes each byte or short operand to int when evaluating an
expression. However, automatic promotion can cause confusion to the compiler. For
example:
byte b=30;
b=b*2; //error
When b*2 is evaluated, it is promoted to int and cannot be assigned to byte b. Otherwise
this can be written as:
b=(byte)(b*2);
NB: Java Promotion rules:
All byte and short values are promoted to int. If one operand is a long, the whole
expression is promoted to long. If one operand is float, the expression is promoted to
float, and if one operand is double, the expression is converted to double.
Arrays
Arrays in Java are different than they are in other languages. Arrays in Java are actual
objects that can be passed around and treated just like other objects.
Arrays are a way to store a list of items of the same type. Each slot of the array holds an
individual element, and you can place elements into or change the contents or those slots
as you need to.
Arrays can contain any type of element value (primitive types or objects). You can have
an array of integers, or an array of strings, or an array of arrays, but you can't have an
array that contains, for example, both strings and integers.
To create an array in Java, you use three steps:
1. Declare a variable to hold the array.
2. Create a new array object and assign it to the array variable.
3. Store things in that array.
25
Declaring Array Variables
Array variables indicate the type of object the array will hold (just as they do for any
variable) and the name of the array, followed by empty brackets ([]). The following are
all typical array variable declarations:
Int monthDays [];
Point hits[];
int temps[];
An alternate method of defining an array variable is to put the brackets after the type
instead of after the variable. They are equivalent, but this latter form is often much more
readable. So, for example, these three declarations could be written like this:
Int[]monthDays;
Point[] hits;
int[] temps;
Creating Array Objects
The second step is to create an array object and assign it to that variable. There are two
ways to do this:
 Using new
 Directly initializing the contents of that array
Using new operator
The first way is to use the new operator to create a new instance of an array:
int[] monthDays = new int[31];
That line creates a new array of thirty one integers. When you create a new array object
using new, you must indicate how many slots that array will hold.
When you create an array object using new, all its slots are initialized for you (0 for
numeric arrays, false for boolean, '\0' for character arrays, and null for objects). You can
also create and initialize an array at the same time.
Direct Initialization
Instead of using new to create the new array object, enclose the elements of the array
inside braces, separated by commas:
String[] chiles = { "jalapeno", "anaheim", "serrano", "habanero", "thai" };
Each of the elements inside the braces must be of the same type and must be the same
type as the variable that holds that array. An array the size of the number of elements
you've included will be automatically created for you. This example creates an array of
String objects named chiles that contains five elements.
Accessing Array Elements
Once you have an array with initial values, you can test and change the values in each
slot of that array. To get at a value stored within an array, use the array subscript
expression:
26
myArray[subscript];
The myArray part of this expression is a variable holding an array object. The subscript
expression specifies the slot within the array to access. Array subscripts start with 0, as
they do in C and C++. So, an array with ten elements has ten array slots accessed using
subscript 0 to 9. Note that all array subscripts are checked to make sure that they are
inside the boundaries of the array (greater than or equal to 0 but less than the array's
length) either when your Java program is compiled or when it is run. It is impossible in
Java to access or assign a value to an array slot outside of the boundaries of the array.
Changing Array Elements
To assign an element value to a particular array slot, merely put an assignment statement
after the array access expression:
myarray[1] = 15;
sentence[0] = "The";
sentence[10] = sentence[0];
Multidimensional Arrays
Java does not support multidimensional arrays. However, you can declare and create an
array of arrays (and those arrays can contain arrays, and so on, for however many
dimensions you need), and access them as you would C-style multidimensional arrays:
int coords[][] = new int[12][12];
coords[0][0] = 1;
coords[0][1] = 2;
Expressions and Operators
Expressions are the simplest form of statement in Java that actually accomplishes
something. Expressions are statements that return a value. Operators are special symbols
that are commonly used in expressions. Arithmetic and tests for equality and magnitude
are common examples of expressions. Because they return a value, you can assign that
result to a variable or test that value in other Java statements.
Operators in Java include arithmetic, various forms of assignment, increment and
decrement, and logical operations.
Arithmetic Operators
Java has five operators for basic arithmetic as shown in the following table:
Operator
+
–
*
/
%
++
+=
-=
Meaning
Addition
Subtraction
Multiplication
Division
Modulus
Increment
Addition Assignment
Subtraction Assignment
27
Example
3+4
5–7
5*5
14 /7
20 % 7
X++ or ++x
X+=1
X-=1
*=
/=
%=
--
Multiplication Assignment
Division Assignment
Modulus Assignment
Decrement
X*=1
X/=1
X%=1
X—or --x
Each operator takes two operands, one on either side of the operator. The operands
cannot be Boolean type.
The subtraction operator (–) can also be used to negate a single operand.
Integer division results in an integer. Because integers don’t have decimal fractions, any
remainder is ignored. The expression 31/9, for example, results in 3 (9 goes into 31 only
3 times).
Modulus (%) gives the remainder once the operands have been evenly divided. For
example, 31 % 9 results in 4 because 9 goes into 31 three times, with 4 left over.
Note that, for integers, the result type of most operations is an int or a long, regardless of
the original type of the operands. Large results are of type long; all others are int.
Arithmetic operation where one operand is an integer and another is a floating point
results in a floating-point result.
The Assignment operators are used to combine arithmetic operations with assignments.
For example,
a = a +4; can be rewritten as,
a += 4;
The increment operators can be used in both postfix and prefix notation. For example:
y=++x; is equivalent to the following two lines:
x=x+1;
y=x;
y=x++; is equivalent to the following two lines:
y=x;
x=x+1;
Comparisons (Relational)
Java has several expressions for testing equality and magnitude. All of these expressions
return a boolean value (that is, true or false).
The following shows the comparison operators:
Operator
==
!=
<
Meaning
Equal to
Not equal to
Less than
Example
x == 3
x != 3
x<3
28
>
<=
>=
Greater than
Less than or equal to
Greater than or equal to
x>3
x <=3
x >=3
Logical Operators
Expressions that result in boolean values (for example, the comparison operators) can be
combined by using logical operators that represent the logical combinations AND, OR,
XOR, and logical NOT.
Operator
&
|
^
||
&&
&=
|=
^=
==
!=
?:
Meaning
Logical AND
Logical OR
Logical XOR(Exclusive OR)
Short Circuit OR
Short Circuit AND
AND Assignment
OR Assignment
XOR Assignment
Equal to
Not equal to
Ternary if then else
For AND combinations, use either the & or &&. The expression will be true only if both
operands tests are also true; if either expression is false, the entire expression is false. The
difference between the two operators is in expression evaluation. Using &, both sides of
the expression are evaluated regardless of the outcome. Using &&, if the left side of the
expression is false, the entire expression returns false, and the right side of the expression
is never evaluated.
For OR expressions, use either | or ||. OR expressions result in true if either or both of the
operands is also true; if both operands are false, the expression is false. As with & and
&&, the single | evaluates both sides of the expression regardless of the outcome; with ||,
if the left expression is true, the expression returns true and the right side is never
evaluated. In addition, there is the XOR operator ^, which returns true only if its operands
are different (one true and one false, or vice versa) and false otherwise (even if both are
true).
In general, only the && and || are commonly used as actual logical combinations. &, |,
and ^ are more commonly used for bitwise logical operations.
For NOT, use the ! operator with a single expression argument. The value of the NOT
expression is the negation of the expression; if x is true, !x is false.
Bitwise Operators
All are inherited from C and C++ and are used to perform operations on individual bits in
integers. The following is summarizes the bitwise operators.
29
Operator
&
|
^
<<
>>
>>>
~
<<=
>>=
>>>=
x&=y
x|=y
x^=y
Meaning
Bitwise AND
Bitwise OR
Bitwise XOR
Left shift
Right shift
Zero fill right shift
Bitwise complement (NOT)
Left shift assignment (x = x << y)
Right shift assignment (x = x >> y)
Zero fill right shift assignment (x = x >>> y)
AND assignment (x = x & y)
OR assignment (x + x | y)
NOT assignment (x = x ^ y)
The following examples show the bitwise operations on numerical data:
Bitwise NOT(~):
42 – 0010 1010
- 1101 0101
Bitwise OR(|):
42 – 0010 1010
15 – 0000 1111
47 – 0010 1111
Bitwise AND(&):
42 – 0010 1010
15 – 0000 1111
10 – 0000 1010
The following simple code in java is used to operate on bits using the above:
int a=42;
int b=15;
int c=a|b;
System.out.println(c);
Operator Precedence
Operator precedence determines the order in which expressions are evaluated. This, in
some cases, can determine the overall value of the expression. For example, take the
following expression:
y=6+4/2
Depending on whether the 6 + 4 expression or the 4/2 expression is evaluated first, the
value of y can end up being 5 or 8. In general, increment and decrement are evaluated
before arithmetic, arithmetic expressions are evaluated before comparisons, and
30
comparisons are evaluated before logical expressions. Assignment expressions are
evaluated last.
The following table shows the specific precedence of the various operators in Java.
Operators further up in the table are evaluated first; operators on the same line have the
same precedence and are evaluated left to right based on how they appear in the
expression itself. For example, in the expression y = 6 + 4 /2, according to this table, that
division is evaluated before addition, so the value of y will be 8.
Operator
. [] ()
++ –– ! ~
instanceof
new(type)
expression
*/%
+–
<< >> >>>
< > <= >=
== !=
&
^
|
&&
||
?:
= += –= *=
%= ^= &=
|= <<= >>=
>>>=
Notes
Parentheses () group expressions; dot (.) is used for access to
methods and variables within objects and classes; [] is used for arrays
Returns true or false based on whether the object is an instance of the
named class or any of that class’s superclasses
The new operator is used for creating new instances of classes; ()
in this case is for casting a value to another type
Multiplication, division, modulus
Addition, subtraction
Bitwise left and right shift
Relational comparison tests
Equality
AND
XOR
OR
Logical AND
Logical OR
Shorthand for if...then...else (discussed on Day 5)
Various assignments
You can always change the order in which expressions are evaluated by using
parentheses around the expressions you want to evaluate first. You can nest parentheses
to make sure expressions evaluate in the order you want them to (the innermost
parenthetical expression is evaluated first). The following expression results in a value of
5, because the 6 + 4 expression is evaluated first, and then the result of that expression
(10) is divided by 2:
y = (6 + 4) / 2
Parentheses also can be useful in cases where the precedence of an expression isn’t
immediately clear—in other words, they can make your code easier to read. Adding
parentheses doesn’t hurt, so if they help you figure out how expressions are evaluated, go
ahead and use them.
31
String Arithmetic
One special expression in Java is the use of the addition operator (+) to create and
concatenate strings. For example:
System.out.println(name + " is a " + color " beetle");
The output of that line (to the standard output) is a single string, with the values of the
variables (here, name and color), inserted in the appropriate spots in the string. The +
operator, when used with strings and other objects, creates a single string that contains
the concatenation of all its operands. If any of the operands in string concatenation is not
a string, it is automatically converted to a string, making it easy to create these sorts of
output lines.
CONTROL FLOW STATEMENTS
Java control statements include:
1. Selection statements
2. Iteration statements (loops)
3. Jump statements
Selection Statements
Java supports two selection statements namely if and switch.
if Conditionals
The if conditional, which enables you to execute different paths based on a simple test. It
has the following syntax:
If(condition) Statement1;
else satement2;
For example:
if (x < y)
System.out.println("x is smaller than y");
The optional else keyword provides the statement to execute if the test is false:
if (x < y)
System.out.println("x is smaller than y");
else System.out.println("y is bigger");
if (engineState == true )
System.out.println("Engine is already on.");
else {
System.out.println("Now starting Engine.");
if (gasLevel >= 1)
engineState = true;
else System.out.println("Low on gas! Can't start engine.");
32
}
This example uses the test (engineState == true). For boolean tests of this type, a
common shortcut is merely to include the first part of the expression, rather than
explicitly testing its value against true or false:
if (engineState)
System.out.println("Engine is on.");
else System.out.println("Engine is off.");
Multiple statements are enclosed inside the braces{}. A nested if is an if statement inside
another if statement.
An if-else if ladder is a common programming construct. The following is a simple
example:
int n=2
if(n=0)
System.out.println(“n is zero”);
else if(n=1)
System.out.println(“n is one”);
else if(n=0)
System.out.println(“n is two”);
else
System.out.println(“n is not defined”);
Statements are executed top down. When one of the conditions is true, the statements(s)
associated with it is executed and the rest of the ladder is bypassed. If none of the
conditions is true, the final else statement is executed. If there is no else, no action will be
taken when all conditions are false.
The Conditional Operator
An alternative to using the if and else keywords in a conditional statement is to use the
conditional operator, sometimes called the ternary operator.
The conditional operator is a ternary operator because it has three terms.
The conditional operator is an expression, meaning that it returns a value (unlike the
more general if, which only can result in a statement or block being executed). The
conditional operator is most useful for very short or simple conditionals, and looks like
this:
test ? trueresult : falseresult
The test is an expression that returns true or false, just like the test in the if statement. If
the test is true, the conditional operator returns the value of trueresult; if it's false, it
returns the value of falseresult. For example, the following conditional tests the values of
x and y, returns the smaller of the two, and assigns that value to the variable smaller:
int smaller = x < y ? x : y;
The conditional operator has a very low precedence; that is, it's usually evaluated only
after all its subexpressions are evaluated. The only operators lower in precedence are the
assignment operators.
33
switch Conditionals
A common programming practice in any language is to test a variable against some
value, and if it doesn't match that value, to test it again against a different value, and if it
doesn't match that one to make yet another test, and so on. Using only if statements, this
can become unwieldy, depending on how it's formatted and how many different options
you have to test. For example, you might end up with a set of if statements something
like this or longer:
if (oper == '+')
addargs(arg1, arg2);
else if (oper == '-')
subargs(arg1, arg2);
else if (oper == '*')
multargs(arg1, arg2);
else if (oper == '/')
divargs(arg1, arg2);
This form of if statement is called a nested if, because each else statement in turn
contains yet another if, and so on, until all possible tests have been made.
A common shorthand mechanism for nested ifs that you can use in some cases allows
you to group tests and actions together in a single statement. This is the switch or case
statement:
switch (test) {
case valueOne:
System.out.println(“n is zero”);
break;
case valueTwo:
resultTwo;
break;
case valueThree:
resultThree;
break;
...
default: defaultresult;
}
In the switch statement, the test (a primitive type of byte, char, short, or int) is compared
with each of the case values in turn. If a match is found, the statement, or statements after
the test is executed. If no match is found, the default statement is executed. The default is
optional, so if there isn't a match in any of the cases and default doesn't exist, the switch
statement completes without doing anything.
Note that the significant limitation of the switch in Java is that the tests and values can be
only simple primitive types (and then only primitive types that are castable to int). You
cannot use larger primitive types (long, float), strings, or other objects within a
switch, nor can you test for any relationship other than equality. This limits the
usefulness of switch to all but the simplest cases; nested ifs can work for any kind of test
on any type.
Here's a simple example of a switch statement similar to the nested if shown earlier:
int n=2;
34
switch (n) {
case 1:
System.out.println(“n is zero”);
break;
case 2:
System.out.println(“n is one”);
break;
case 3:
System.out.println(“n is two”);
break;
default:
System.out.println(“n is not defined”);
break;
}
Note the break statement included in every line. Without the explicit break, once a match
is made, the statements for that match and also all the statements further down in the
switch are executed until a break or the end of the switch is found (and then execution
continues after the end of the switch). In some cases, this may be exactly what you want
to do, but in most cases, you'll want to make sure to include the break so that only the
statements you want to be executed are executed.
One handy use of falling through occurs when you want multiple values to execute the
same statements. In this instance, you can use multiple case lines with no result, and the
switch will execute the first statements it finds. For example, in the following switch
statement, the string "x is an even number." is printed if x has values of 2, 4, 6, or 8. All
other values of x print the string "x is an odd number."
switch (x) {
case 2:
case 4:
case 6:
case 8:
System.out.println("x is an even number.");
break;
default: System.out.println("x is an odd number.");
}
A nested switch is a switch within a switch. Since each switch is a block, no conflict can
arise between inner and outer blocks.
Iteration Statements
The Java iteration statements are:
 for loop
 while loop, and
 do-while loop
while Loop (pretest loop)
The while loop is used to repeat a statement or block of statements as long as a particular
condition is true. while loops look like this:
35
while (condition) {
bodyOfLoop;
}
The condition is a boolean expression. If it returns true, the while loop executes the
statements in bodyOfLoop and then tests the condition again, repeating until the
condition is false. You can use a single statement in place of the block.
Here's an example of a while loop that outputs ten integers from 10 down to 1:
int n=10;
while(n>0){
System.out.println(“n is: “+n);
n--;
}
do...while Loop (post test loop)
The main difference is that while loops test the condition before looping, making it
possible that the body of the loop will never execute if the condition is false the first time
it's tested. do loops run the body of the loop at least once before testing the condition. do
loops look like this:
do {
bodyOfLoop;
} while (condition);
Here, the bodyOfLoop part is the statements that are executed with each iteration. It's
shown here with a block statement because it's most commonly used that way, but you
can substitute the braces for a single statement as you can with the other control-flow
constructs. The condition is a boolean test. If it returns true, the loop is run again. If it
returns false, the loop exits. Keep in mind that with do loops, the body of the loop
executes at least once.
Here's a simple example of a do loop that prints a message each time the loop iterates:
int n=10;
do{
System.out.println(“n is: “+n);
n--;
} while(n>0);
The above code can be written as:
int n=10;
do{
System.out.println(“n is: “+n);
} while(--n>0);
for Loops
The for loop, repeats a statement or block of statements some number of times until a
condition is matched. for loops are frequently used for simple iteration in which you
repeat a block of statements a certain number of times and then stop, but you can use for
loops for just about any kind of loop.
The for loop in Java looks roughly like this:
for (initialization; test; increment) {
36
statements;
}
The start of the for loop has three parts:
 initialization is an expression that initializes the start of the loop. If you have a loop
index, this expression might declare and initialize it, for example, int i = 0. Variables
that you declare in this part of the for loop are local to the loop itself; they cease
existing after the loop is finished executing.
 test is the test that occurs after each pass of the loop. The test must be a boolean
expression or function that returns a boolean value, for example, i < 10. If the test is
true, the loop executes. Once the test is false, the loop stops executing.
 increment is any expression or function call. Commonly, the increment is used to
change the value of the loop index to bring the state of the loop closer to returning
false and completing.
The statement part of the for loop is the statements that are executed each time the loop
iterates. Just as with if, you can include either a single statement here or a block; the
previous example used a block because that is more common. Here's an example of a for
loop that displays the integers 10 down to 1 in descending order:
for (int i = 10; i >0; i--){
System.out.println(“i is: “+i);
}
Commas can be used when you want to include more than one statement in the
initialization and iteration portions on the for loop. For example:
for (int a=1,b=4; a b; a++,b--){
System.out.println(“a and b: “+a + “ “ + b);
}
Jump Statements
Java supports three jump statements namely break, continue and return. These statements
transfer program control to another part of the program
You've already seen break as part of the switch statement; it stops execution of the
switch, and the program continues.
break statement
The break keyword, when used with a loop, immediately halts execution of the current
loop. If you've nested loops within loops, it breaks out of the innermost loop.
For example, take a for loop that displays a 100 integers from 0 to 99. You can test the
loop and use break to halt the loop if the condition is met:
for (int i = 0; i <100; i++){
if(i==10) break;
System.out.println(“i is: “+i);
}
System.out.println(“Loop exited”);
continue
37
It is similar to break except that instead of halting execution of the loop entirely, the loop
starts over at the next iteration. It stops processing the remainder of the code for a
particular iteration. Foe example:
for (int i = 0; i <10; i++){
System.out.println(“i is: “+i);
if(i%2===0) break;
System.out.println(“”);
}
return statement
It is used to explicitly return from a method, that is, it causes the back to the caller of the
method. Thus, it immediately terminates the method in which it is executed.
Labeled Loops
Both break and continue can have an optional label that tells Java where to break to.
Without a label, break jumps outside the nearest loop (to an enclosing loop or to the next
statement outside the loop), and continue restarts the enclosing loop. Using labeled
breaks and continues enables you to break outside nested loops or to continue a loop
outside the current loop.
To use a labeled loop, add the label before the initial part of the loop, with a colon
between them. Then, when you use break or continue, add the name of the label after the
keyword itself:
out:
for (int i = 0; i <10; i++) {
while (x < 50) {
if (i * x == 400)
break out;
...
}
...
}
In this snippet of code, the label out labels the outer loop. Then, inside both the for and
the while loop, when a particular condition is met, a break causes the execution to break
out of both loops.
Here's another example: the following program contains a nested for loop. Inside the
innermost loop, if the summed values of the two counters is greater than four, both loops
exit at once:
foo:
for (int i = 1; i <= 5; i++)
for (int j = 1; j <= 3; j++) {
System.out.println("i is " + i + ", j is " + j);
if ((i + j) > 4)
break foo;
}
System.out.println("end of loops");
38
Here's the output from this program:
i is 1, j is 1
i is 1, j is 2
i is 1, j is 3
i is 2, j is 1
i is 2, j is 2
i is 2, j is 3
end of loops
As you can see, the loop iterated until the sum of i and j was greater than 4, and then both
loops exited back to the outer block and the final message was printed.
Exceptions and Exception handling
A java exception is an object that describes an exceptional (error) condition that has
occurred in a piece of code. An exception is an abnormal condition that arises in a code
sequence at runtime.
When an exceptional condition occurs, an object representing that condition is created
and thrown in the method that caused the error. The method may handle the exception
itself or pass it on. Either way, the exception is caught and processed.
Exceptions can be generated by java runtime system or manually generated by your code.
Java exception handling is managed by five keyword ; try, catch, throw, throws and
finally.
Exception Types
All exception types are subclasses of built in class Throwable. Immediate below
Throwable are two subclasses that partition exceptions into two distinct branches:
1. Exception Class - This class is used for exceptional conditions that user programs
should catch. It is also the class you will subclass to create your own custom
exception types. RunTimeException is an important subclass of Exception.
2. Error – This include exceptions to be caught under normal circumstances by your
program. It is used by java runtime system to indicate errors having to do with
runtime environment itself eg stack overflow.
Uncaught exceptions
The following program causes a divide overflow error.
class Exc0{
public static void main(String[] args){
int d=0;
int a =42/d;
}
}
Java runtime system detects the error, constructs a new exception object and then throws
this exception. The following output is generated by standard JDK runtime interpreter.
Java.lang.ArithmeticException: /by zero
39
at Exc0.main(Exc0.java:4)
The type of exception thrown (ArithmeticException) is a subclass of Exception class. The
stack will show the sequence of method invocation that led up to the error. For example:
class Exc1{
static void subroutine(){
int d=0;
int a =42/d;
}
public static void main(String[] args){
Exc1.subroutine();
}
}
The output becomes:
Java.lang.ArithmeticException: /by zero
at Exc1.subroutine(Exc1.java:4)
at Exc1.main(Exc1.java:4)
Using Try and Catch
class Exc2{
public static void main(String[] args){
int d,a;
try{
d=0;
a=42/d;
System.out.println("This wil not be printed");
}catch(ArithmeticException e){
System.out.println("Exception: "+e);
}
System.out.println("After Catching");
}
}
Multiple Catch clauses
A program may raise more than one exception. Thus it is possible to 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 to match is executed. The others
are bypassed.
class MultiCatch{
public static void main(String[] args){
try{
int a=args.length;
System.out.println("a = " +a);
40
int b=42/a;
int c[]={1};
c[3]=78;
}catch(ArithmeticException e){
System.out.println("Divide by Zero: "+e);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Array Index out of Bounds: "+e);
}
System.out.println("After try catch blocks");
}
}
NB: In the multiple catch statements, the subclass exceptions must come before their
superclasses. The following program produces an error because the class Exception
appears before the subclass ArithmeticException.
class SupreSubCatch{
public static void main(String[] args){
try{
int a=0;
int b=42/a;
}catch(Exception e){
System.out.println("Generic Exception”);
}catch(ArithmeticException e){
System.out.println("Never reached”);
}
}
}
The second catch is never reached.
Nested Try statements
A try statement can be inside the block of another try. Each time a try statement is
entered, the context of the exception is pushed on the stack.
Throw
The previous examples catch exceptions thrown by the java runtime system. It is possible
for a java program to throw an exception explicitly, using the throw statement. There are
two ways to obtain a throwable object:
1. Using a parameter into a catch statement.
2. Creating a throwable object with new operator.
NB: Throwable object must be of type Throwable or of its subclasses. Simple types such
as int or char or non-throwable classes such as string and object cannot be used as
exceptions. An example:
class ThrowDemo{
static void demoProc(){
41
try{
throw new NullPointerException("Demo");
}catch(NullPointerException e){
System.out.println("Caught inside Demoproc");
throw e; //rethrow the exception
}
}
public static void main(String[] args){
try{
demoProc();
}catch(NullPointerException e){
System.out.println("Recaught: "+ e);
}
}
}
The flow of execution stops immediately after the throw statement; any subsequent
statement are not executed.
NB: All java built-in run-time exceptions have two constructors; one with no parameter
and one that takes a string [parameter.
Throws
If a method causes an exception it can not handle , it must specify this behaviour so that
the caller of the method can guard themselves against such an exception. A throws clause
lists the types of exceptions that a method might throw. For example:
class ThrowDemo1{
static void throwOne() throws IllegalAccessException{
System.out.println("Inside throwOne");
throw new IllegalAccessException("Demo");
}
public static void main(String[] args){
try{
throwOne();
}catch(IllegalAccessException e){
System.out.println("Caught: "+ e);
}
}
}
Finally
Finally create a block of code that will be executed after a try/catch block has completed
and before the code following the try/catch block. Therefore, it will execute whether or
not an exception is thrown. An Example:
42
class FinallyDemo{
//throw an exception out of method
static void procA(){
try{
System.out.println("Inside procA");
throw new RuntimeException("Demo");
}finally{
System.out.println("procA finally");
}
}
//return from within a try block
static void procB(){
try{
System.out.println("Inside procB");
return;
}finally
{
System.out.println("procB finally");
}
}
//execute a try block normally
static void procC(){
try{
System.out.println("Inside procC");
}finally{
System.out.println("procC finally");
}
}
public static void main(String[] args){
try{
procA();
}catch(Exception e){
System.out.println("Exception Caught");
}
procB();
procC();
}
}
When procA is called, an exception is thrown and then finally executed.
In procB, the try statement is exited by return, then finally executed.
In procC, try executes normally, then finally excutes.
43
Keyboard input in Java
In stand-alone Java programs, we have a few options:
 Use System.in (counterpart of System.out)
 Course input through the command line
 Course input through a popup window (JOptionPane)
Strings
It is simplest to just consider String input
For numeric input, just convert the String to a number
 i = Integer.parseInt( s ) for ints
 d = Double.parseDouble( s ) for doubles
public class AddNumbers
{
public static void main( String args[] )
{
int x = Integer.parseInt( args[0] );
int y = Integer.parseInt( args[1] );
int sum = x+y;
System.out.println("Sum is: "+sum);
}
}
Create and compile the AddNumbers.java application
Execute the program for the following numbers
 java AddNumbers 555 222
 java AddNumbers 1000000000 1000000000
 java AddNumbers 2000000000 2000000000
Using System.in
Input can be coursed through the System.in object
To make things simple, we need to “convert” System.in into an object where we could
call a readLine() method
Converting System.in to a BufferedReader object
1. Conversion involves File IO objects (make sure to import java.io.*):
InputStreamReader reader = new
InputStreamReader( System.in );
BufferedReader buf = new BufferedReader( reader );
2. Then, call readLine() on buf to initiate input:
String s = buf.readLine();
Example
import java.io.*;
public class KInputExample
{
44
public static void main(String[] argv) throws IOException
{
// code needed for keyboard input
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Type First Number");
int x=Integer.parseInt(br.readLine().trim());
System.out.println("Type Second Number");
int y=Integer.parseInt(br.readLine().trim());
int sum=x+y;
System.out.println("sum is :"+ sum);
}
}
1. String values from the keyboard (no conversion necessary):
String dataValue; // declares the variable to hold the String value
dataValue = in.readLine(); // reads the String from the keyboard
// into the variable dataValue
2. integer (int) values from the keyboard (convert from String to int)
int dataValue; // declares the variable to hold the integer value
dataValue = Integer.parseInt(in.readLine().trim()); // reads the String
// from the keyboard, trims off any blank
// spaces and converts the String to an int
3. double values from the keyboard (convert from String to double)
double dataValue; // declares the variable to hold the double value
dataValue = Double.parseDouble(in.readLine().trim()); // reads
// the String from the keyboard, trims off any
// blank spaces, converts the String into a double
If you
want to use the input as anything other than a string it needs to be converted into
the right variable type. Java provides a way to do this as shown in the examples below
x = Double.parseDouble(temp);
// string temp converted to double x
y = Float.parseFloat(temp);
// string temp converted to float y
i = Long.parseLong(temp);
// string temp converted to long i
j = Integer.parseInt(temp);
// string temp converted to int j
k = Short.parseShort(temp);
// string temp converted to short k
m = Byte.parseByte(temp);
// string temp converted to byte m
a = Boolean.valueOf(temp).booleanValue(); // string temp converted to
boolean a
Input Using JOptionPane
1. Create a JOptionPane object
 JOptionPane is a javax.swing.* class
45
2. Call showInputDialog(s) on the object, where s is a prompt describing what needs to
be input
 method returns the String that is input through the dialog window
 window closes upon entry of string
If you use javax.swing.* objects, program termination is not automatic
If a JOptionPane object is created, the program will not stop even if you reach the end of
main()
You need to terminate explicitly
System.exit( 0 );
as the last statement in main()
Example
import javax.swing.*;
public class JOptionExample
{
public static void main(String[] argv)
{
int x=Integer.parseInt(JOptionPane.showInputDialog("Type First Number"));
int y=Integer.parseInt(JOptionPane.showInputDialog("Type Second Number"));
int sum=x+y;
JOptionPane.showMessageDialog(null,"Sum is :
"+sum,"Greetings",JOptionPane.PLAIN_MESSAGE);
System.exit(0);
}
}
AWT (i.e. ABSTRACT WINDOW TOOLKIT) COMPONENTS/GRAPHIC
COMPONENTS
These are the major components you can work with in the AWT:
 Containers. Containers are generic AWT components that can contain other
components, including other containers. The most common form of container is
the panel, which represents a container that can be displayed on screen. Applets
are a form of panel (in fact, the Applet class is a subclass of the Panel class).
 Canvases. A canvas is a simple drawing surface. Although you can draw on
panels (as you've been doing all along), canvases are good for painting images or
other graphics operations.
 UI components. These can include buttons, lists, simple popup menus,
checkboxes, test fields, and other typical elements of a user interface.
 Window construction components. These include windows, frames, menubars,
and dialogs. These are listed separately from the other UI components because
you'll use these less often—particularly in applets. In applets, the browser
provides the main window and menubar, so you don't have to use these. Your
applet may create a new window, however, or you may want to write your own
Java application that uses these components.
The classes inside the java.awt package are written and organized to mirror the abstract
structure of containers, components, and individual UI components
46
The Basic User Interface Components
The simplest form of AWT component is the basic UI component. You can create and
add these to your applet without needing to know anything about creating containers or
panels—your applet, even before you start painting and drawing and handling events, is
already an AWT container. Because an applet is a container, you can put other AWT
components—such as UI components or other containers—into it.
The procedure for creating the component is the same:
 you first create the component, and
 then add it to the panel that holds it, at which point it is displayed on the screen.
To add a component to a panel (such as your applet, for example), use the add()
method:
public void init() {
Button b = new Button("OK");
add(b);
}
Labels
Labels are, effectively, text strings that you can use to label other UI components.
The advantages that a label has over an ordinary text string is that it follows the layout of
the given panel, and you don't have to worry about repainting it every time the panel is
redrawn. Labels also can be easily aligned within a panel, enabling you to attach labels to
other UI components without knowing exact pixel positions.
To create a label, use one of the following constructors:
 Label() creates an empty label, with its text aligned left.
 Label(String) creates a label with the given text string, also aligned left.
 Label(String, int) creates a label with the given text string and the given
alignment. The available alignments are stored in class variables in Label, making
them easier to remember: Label.RIGHT, Label.LEFT, and Label.CENTER.
The label's font is determined by the overall font for the component (as set by the
setFont() method).
Buttons
Buttons are simple UI components that trigger some action in your interface when they
are pressed. For example, a calculator applet might have buttons for each number and
operator, or a dialog box might have buttons for "OK" and "Cancel."
To create a button, use one of the following constructors:
 Button() creates an empty button with no label.
 Button(String) creates a button with the given string object as a label.
Once you have a button object, you can get the value of the button's label by using the
getLabel() method and set the label using the setLabel(String) methods.
Checkboxes
Checkboxes can be selected or deselected to provide options.
Checkboxes are user interface components that have two states: on and off (or checked
and unchecked, selected and unselected, true and false, and so on). Unlike buttons,
47
checkboxes usually don't trigger direct actions in a UI but, instead, are used to indicate
optional features of some other action.
Checkboxes can be created by using the Checkbox class. You can create a checkbox by
using one of the following constructors:
 Checkbox() creates an empty checkbox, unselected.
 Checkbox(String) creates a checkbox with the given string as a label.
 Checkbox(String, null, boolean) creates a checkbox that is either selected or
unselected based on whether the boolean argument is true or false, respectively.
(The null is used as a placeholder for a group argument. Only radio buttons have
groups, as you'll learn in the next section).
Radio Buttons
Radio buttons are a variation on the checkbox.
Radio buttons have the same appearance as checkboxes, but only one in a series can be
selected at a time.
To create a series of radio buttons, first create an instance of CheckboxGroup:
CheckboxGroup cbg = new CheckboxGroup();
Then create and add the individual checkboxes, using the group as the second argument,
and whether or not that checkbox is selected (only one in the series can be selected):
add(new Checkbox("Yes", cbg, true));
add(new Checkbox("no", cbg, false));
Choice Menus
The choice menu is a more complex UI component than labels, buttons, or checkboxes.
Choice menus are popup (or pulldown) menus that enable you to select an item from that
menu. The menu then displays that choice on the screen.
To create a choice menu, create an instance of the Choice class, and then use the
addItem() or add() method to add individual items to it in the order in which they should
appear:
Choice c = new Choice();
c.addItem("Apples");
c.addItem("Oranges");
c.addItem("Strawberries");
c.addItem("Blueberries");
c.addItem("Bananas");
Finally, add the entire choice menu to the panel in the usual way:
add(c);
Scrolling Lists
A scrolling list is functionally similar to a choice menu in that it lets you pick several
options from a list. Scrolling lists differ in two significant ways:
 Scrolling lists are not popup menus. They're lists of items in which you can
choose one or more items from a list. If the number of items is larger than the list
box, a scrollbar is automatically provided so that you can see the other items.
 A scrolling list can be defined to accept only one item at a time (exclusive), or
multiple items (nonexclusive).
48
To create a scrolling list, create an instance of the List class and then add individual items
to that list. The List class has two constructors:
 List() creates an empty scrolling list that enables only one selection at a time.
 List(int, boolean) creates a scrolling list with the given number of visible lines on
the screen (you're unlimited as to the number of actual items you can add to the
list). The boolean argument indicates whether this list enables multiple selections
(true) or not (false).
After creating a List object, add items to it using the addItem() method and then add the
list itself to the panel that contains it. Here's an example:
List lst = new List(5, true);
lst.addItem("Hamlet");
lst.addItem("Claudius");
lst.addItem("Gertrude");
lst.addItem("Polonius");
lst.addItem("Horatio");
lst.addItem("Laertes");
lst.addItem("Ophelia");
add(lst);
Text Fields
Unlike the UI components up to this point, which enable you to select only among
several options to perform an action, text fields allow you to enter any values.
Text fields enable your reader to enter text.
To create a text field, use one of the following constructors:
 TextField() creates an empty TextField 0 characters wide.
 TextField(int) creates an empty text field with the given width in characters.
 TextField(String) creates a text field 0 characters wide, initialized with the given
string.
 TextField(String, int) creates a text field with the given width in characters and
containing the given string. If the string is longer than the width, you can select
and drag portions of the text within the field and the box will scroll left or right.
For example, the following line creates a text field 30 characters wide with the string
"Enter Your Name" as its initial contents.
TextField tf = new TextField("Enter Your Name", 30);
add(tf);
Tip: Text fields include only the editable field itself. You usually need to include a label
with a text field to indicate what belongs in that text field.
Note: Text fields are different from text areas; text fields are limited in size and are
best used for one-line items, whereas text areas have scrollbars and are better for
larger text windows. Both can be edited and enable selections with the mouse. You'll
learn about text areas later today.
49
Text Areas
Text areas are like text fields, except they have more functionality for handling large
amounts of text. Because text fields are limited in size and don't scroll, they are better for
one-line responses and text entry; text areas can be any given width and height and have
scrollbars by default, so you can deal with larger amounts of text more easily.
To create a text area, use one of the following constructors:
 TextArea() creates an empty text area 0 rows long and 0 characters wide. Given
that a text area with no dimensions can't be displayed, you should make sure you
change the dimensions of this new text area before adding it to a panel (or just use
the next constructor instead).
 TextArea(int, int) creates an empty text area with the given number of rows and
columns (characters).
 TextArea(String) creates a text area displaying the given string, 0 rows by 0
columns.
 TextArea(String, int, int) creates a text area displaying the given string and with
the given dimensions.
The following example creates a TextArea to hold data:
String str = "Once upon a midnight dreary, while I pondered, weak and weary,\n"
+
"Over many a quaint and curious volume of forgotten lore,\n" +
"While I nodded, nearly napping, suddenly there came a tapping,\n" +
"As of some one gently rapping, rapping at my chamber door.\n" +
"\"'Tis some visitor,\" I muttered, \"tapping at my chamber door-\n
+ ... ;
add(new TextArea(str,10,60));
Scrollbars and Sliders
Text areas and scrolling lists come with their own scrollbars, which are built into those
UI components and enable you to manage both the body of the area or the list and its
scrollbar as a single unit. You can also create individual scrollbars, or sliders, to
manipulate a range of values.
Scrollbars are used to select a value between a maximum and a minimum value. To
create a scrollbar, you can use one of three constructors:
 Scrollbar() creates a scrollbar with 0, 0 as its initial maximum and initial
minimum values, in a vertical orientation.
 Scrollbar(int) creates a scrollbar with 0, 0 as its initial maximum and initial
minimum values. The argument represents an orientation, for which you can use
the class variables Scrollbar.HORIZONTAL and Scrollbar.VERTICAL.
 Scrollbar(int, int, int, int, int) creates a scrollbar with the following arguments
(each one is an integer, and must be presented in this order):
The first argument is the orientation of the scrollbar: Scrollbar.HORIZONTAL
and Scrollbar.VERTICAL.
The second argument is the initial value of the scrollbar, which should be a value
between the scrollbar's maximum and minimum values.
50
The third argument is the the overall width (or height, depending on the
orientation) of the scrollbar's box. In user interface design, a larger box implies
that a larger amount of the total range is currently showing (applies best to things
such as windows and text areas).
The fourth and fifth arguments are the minimum and maximum values for the
scrollbar.
public void init() {
l = new Label("0");
add(l);
add(new Scrollbar(Scrollbar.HORIZONTAL, 1, 0, 1, 100));
}
Layout Managers
The actual appearance of the AWT components on the screen is determined by two
things: the order in which they are added to the panel that holds them, and the layout
manager that panel is currently using to lay out the screen. The layout manager
determines how portions of the screen will be sectioned and how components within that
panel will be placed.
Note that each panel on the screen can have its own layout manager. By nesting panels
within panels, and using the appropriate layout manager for each one, you can often
arrange your UI to group and arrange components in a way that is both functionally
useful and also looks good on a variety of platforms and windowing systems.
The AWT provides five basic layout managers: FlowLayout, GridLayout,
GridBagLayout, BorderLayout, and CardLayout. To create a layout manager for a given
panel, use the setLayout() method for that panel:
public void init() {
setLayout(new FlowLayout());
}
Setting the default layout manager, like creating the user interface
components, is best done during the applet's initialization, which is why it's included
here.
Once the layout manager is set, you can start adding components to the panel. The order
in which components are added is often significant, depending on which layout manager
is currently active. Read on for information about the specific layout managers and how
they present components within the panel to which they apply.
The following sections describe the five basic Java AWT layout managers.
The FlowLayout Class
The FlowLayout class is the most basic of layouts. Using the flow layout, components are
added to the panel one at a time, row by row. If a component doesn't fit onto a row, it's
51
wrapped onto the next row. The flow layout also has an alignment, which determines the
alignment of each row. By default, each row is aligned centered.
To create a basic flow layout with a centered alignment, use the following line of code in
your panel's initialization (because this is the default pane layout, you don't need to
include this line if that is your intent):
setLayout(new FlowLayout());
To create a flow layout with an alignment other than centered, add the
FlowLayout.RIGHT or FlowLayout.LEFT class variable as an argument:
setLayout(new FlowLayout(FlowLayout.LEFT));
You can also set horizontal and vertical gap values by using flow layouts. The gap is the
number of pixels between components in a panel; by default, the horizontal and vertical
gap values are three pixels, which can be very close indeed. Horizontal gap spreads out
components to the left and to the right, vertical gap to the top and bottom of each
component. Add integer arguments to the flow layout constructor to increase the gap (a
layout gap of 10 points in both the horizontal and vertical directions setLayout(new
FlowLayout(FlowLayout.LEFT), 10, 10);
Grid and Grid Bag Layouts
Grid layouts use a layout that offers more control over the placement of components
inside a panel. Using a grid layout, you portion off the area of the panel into rows and
columns. Each component you then add to the panel is placed in a "cell" of the grid,
starting from the top row and progressing through each row from left to right (here's
where the order of calls to the add() method are very relevant to how the screen is laid
out). By using grid layouts and nested grids, you can often approximate the use of hardcoded pixel values to place your UI components precisely where you want them.
To create a grid layout, indicate the number of rows and columns you want the grid to
have when you create a new instance of the GridLayout class:
setLayout(new GridLayout(3, 3));
Grid layouts can also have a horizontal and vertical gap between components; to create
gaps, add those pixel values:
setLayout(new GridLayout(3, 3, 10, 15));
Grid bag layouts, as implemented by the GridBagLayout class, are variations on grid
layouts. Grid bag layouts also enable you to lay out your user interface elements in a
rectangular grid, but with grid bag layouts you have much more control over the
presentation of each element in the grid. Grid bag layouts use a helper class,
GridBagConstraints, to indicate how each cell in the grid is to be formatted.
Border Layouts
Border layouts behave differently from flow and grid layouts. When you add a
component to a panel that uses a border layout, you indicate its placement as a
geographic direction: north, south, east, west, and center.The components around all the
52
edges are laid out with as much size as they need; the component in the center, if any,
gets any space left over.
To use a border layout, you create it as you do the other layouts:
setLayout(new BorderLayout());
Then you add the individual components by using a special add() method: the first
argument to add() is a string indicating the position of the component within the layout:
add("North", new TextField("Title", 50));
add("South", new TextField("Status", 50));
You can also use this form of add() for the other layout managers; the string argument
will just be ignored if it's not needed.
Border layouts can also have horizontal and vertical gaps. Note that the north and south
components extend all the way to the edge of the panel, so the gap will result in less
space for the east, right, and center components. To add gaps to a border layout, include
those pixel values as before:
setLayout(new BorderLayout(10, 10));
Card Layouts
Card layouts are different from the other layouts. Unlike with the other three layouts,
when you add components to a card layout, they are not all displayed on the screen at
once. Card layouts are used to produce slide shows of components, one at a time.
Generally when you create a card layout, the components you add to it will be other
container components—usually panels. You can then use different layouts for those
individual "cards" so that each screen has its own look.
When you add each "card" to the panel, you can give it a name. Then you can use
methods defined on the CardLayout class to move back and forth between different cards
in the layout.
For example, here's how to create a card layout containing three cards:
setLayout(new CardLayout());
Panel one = new Panel()
add("first", one);
Panel two = new Panel()
add("second", two);
Panel three = new Panel()
add("third", three);
show(this, "second");
Insets
Whereas horizontal gap and vertical gap are used to determine the amount of space
between components in a panel, insets are used to determine the amount of space around
the panel itself. The insets class provides values for the top, bottom, left, and right insets,
which are then used when the panel itself is drawn.
To include an inset, override the insets() method in your class (your Applet class or other
class that serves as a panel):
53
public Insets insets() {
return new Insets(10, 10, 10, 10);
}
The arguments to the Insets constructor provide pixel insets for the top, bottom, left, and
right edges of the panel. This particular example provides an inset of 10 pixels on all four
sides of the panel.
Handling UI Actions and Events
For your UI components to do something when they are activated, you need to hook up
the UI's action with an operation.
Testing for an action by a UI component is a form of event management. In particular, UI
components produce the special kind of event called an action. To intercept an action by
any UI component, you define an action() method in your applet or class:
public boolean action(Event evt, Object arg) {
...
}
The action() method should look familiar to the basic mouse and keyboard event
methods. Like those methods, it gets passed the event object that represents this event. It
also gets an extra object, which can be of any type.
What's that second argument for?
The second argument to the action method depends on the UI component that's
generating the event. The basic definition is that it's any arbitrary argument—when a
component generates an event, it can pass along any extra information that might later be
needed. Because that extra information may be useful for you, it's passed on through the
action() method.
All the basic UI components (except for labels, which have no action) have different
actions and arguments:
 Buttons create actions when they are selected, and a button's argument is the label
of the button.
 Checkboxes, both exclusive and nonexclusive, generate actions when a box is
checked. The argument is always true.
 Choice menus generate an action when a menu item is selected, and the argument
is that item.
 Text fields create actions when the user presses Return inside that text field. Note
that if the user tabs to a different text field or uses the mouse to change the input
focus, an action is not generated. Only a Return triggers the action.
Note that with actions, unlike with ordinary events, you can have many different kinds of
objects generating the event, as opposed to a single event such as a mouseDown. To deal
with those different UI components and the actions they generate, you have to test for the
type of object that sent/created the event in the first place inside the body of your action()
method. That object is stored in the event's target instance variable, and you can use the
instanceof operator to find out what kind of UI component sent it:
54
public boolean action(Event evt, Object arg) {
if (evt.target instanceof TextField)
handleText(evt.target);
else if (evt.target instanceof Choice)
handleChoice(arg);
...
}
Although you can handle UI actions in the body of the action() method, it's much more
common simply to define a handler method and call that method from action() instead.
Here, there are two handler methods: one to handle the action on the text field
(handleText()) and one to handle the action on the choice menu (handleChoice()).
Depending on the action you want to handle, you may also want to pass on the argument
from the action, the UI component that sent it, or any other information that the event
might contain.
Here's a simple applet that has five buttons labeled with colors. The action() method tests
for a button action and then passes off the word to a method called changeColor(), which
changes the background color of the applet based on which button was pressed
import java.awt.*;
public class ButtonActionsTest extends java.applet.Applet {
public void init() {
setBackground(Color.white);
add(new Button("Red"));
add(new Button("Blue"));
add(new Button("Green"));
add(new Button("White"));
add(new Button("Black"));
}
public boolean action(Event evt, Object arg) {
if (evt.target instanceof Button)
changeColor((String)arg);
return true;
}
void changeColor(String bname) {
if (bname.equals("Red")) setBackground(Color.red);
else if (bname.equals("Blue")) setBackground(Color.blue);
else if (bname.equals("Green")) setBackground(Color.green);
else if (bname.equals("White")) setBackground(Color.white);
else setBackground(Color.black);
}
}
Nesting Panels and Components
Adding UI components to individual applets is fun, but applets begin to turn into lots of
fun when you begin working with nested panels. By nesting different panels inside your
applet, and panels inside those panels, you can create different layouts for different parts
55
of the overall applet area, isolate background and foreground colors and fonts to
individual parts of an applet, and manage the design of your UI components much more
cleanly and simply. The more complex the layout of your applet, the more likely you're
going to want to use nested panels.
Nested Panels
Panels, as you've already learned, are components that can be actually displayed on
screen; Panel's superclass Container provides the generic behavior for holding other
components inside it. The Applet class, which your applets all inherit from, is a subclass
of Panel. To nest other panels inside an applet, you merely create a new panel and add it
to the applet, just as you would add any other UI component:
setLayout(new GridLayout(1, 2, 10, 10));
Panel panel1 = new Panel();
Panel panel2 = new Panel();
add(panel1);
add(panel2);
You can then set up an independent layout for those subpanels and add AWT components
to them (including still more subpanels) by calling the add() method in the appropriate
panel:
panel1.setLayout(new FlowLayout());
panel1.add(new Button("Up"));
panel1.add(new Button("Down"));
Although you can do all this in a single class, it's common in applets that make heavy use
of the panels to factor out the layout and behavior of the subpanels into separate classes,
and to communicate between the panels by using method calls.
Events and Nested Panels
When you create applets with nested panels, those panels form a hierarchy from the
outermost panel (the applet, usually), to the innermost UI component. This hierarchy is
important to how each component in an applet interacts with the other components in the
applet or with the browser that contains that applet; in particular, the component
hierarchy determines the order in which components are painted to the screen.
More importantly, the hierarchy also affects event handling, particularly for user input
events such as mouse and keyboard events.
Events are received by the innermost component in the component hierarchy and passed
up the chain to the root. Suppose, for example, that you have an applet with a subpanel
that can handle mouse events (using the mouseDown() and mouseUp() methods) and that
panel contains a button. Clicking on the button means that the button receives the event
before the panel does; if the button isn't interested in that mouseDown(), the event gets
passed to the panel, which can then process it or pass it further up the hierarchy.
56
Remember the discussion about the basic event methods yesterday? You learned that the
basic event methods all return boolean values. Those boolean values become important
when you're talking about handling events or passing them on.
An event handling method, whether it is the set of basic event methods or the more
generic handleEvent(), can do one of three things, given any random event:
 Not be interested in the event (this is usually true only for handleEvent(), which
receives all the events generated by the system). If this is the case, the event is
passed on up the hierarchy until a component processes it (or it is ignored
altogether). In this case, the event handling method should return false.
 Intercept the event, process it, and return true. In this case, the event stops with
that event method. Recall that this is the case with the basic mouseDown() and
keyDown() methods that you learned about yesterday.
 Intercept the method, process it, and pass it on to the next event handler. This is a
more unusual case, but you may create a user interface by using nested
components that will want to do this. In this case, the event method should return
false to pass the event on to the next handler in the chain.
More UI Components
Once you master the basic UI components and how to add them to panels and manage
their events, you can add more UI components. In this section, you'll learn about text
areas, scrolling lists, scrollbars, and canvases.
Note that the UI components in this section do not produce actions, so you can't use the
action() method to handle their behavior. Instead, you have to use a generic
handleEvent() method to test for specific events that these UI components generate. ]
Canvases
Although you can draw on most AWT components, such as panels, canvases do little
except let you draw on them. They can't contain other components, but they can accept
events, and you can create animations and display images on them. Canvases, in other
words, could have been used for much of the stuff you learned about earlier this week.
A canvas is a component that you can draw on.
To create a canvas, use the Canvas class and add it to a panel as you would any other
component:
Canvas can = new Canvas();
add(can);
More UI Events
For many basic events, such as mouseDown() and keyDown(), you can define methods
for those events to handle the event directly. You learned a similar mechanism today for
UI actions where creating an action() method handled a specific action generated by a UI
component.
The most general way of managing events, however, continues to be the handleEvent()
method. For events relating to scrollbars and scrolling lists, the only way to intercept
these events is to override handleEvent().
57
To intercept a specific event, test for that event's ID. The available IDs are defined as
class variables in the Event class, so you can test them by name. The table below shows
additonal events that may be useful to you for the components you've learned about today
(or that you might find useful in general).
Additional events.
Event ID
What It Represents
ACTION_EVENT
Generated when a UI component action occurs
KEY_ACTION
Generated when text field action occurs
LIST_DESELECT
Generated when an item in a scrolling list is deselected
LIST_SELECT
Generated when an item in a scrolling list is selected
SCROLL_ABSOLUTE
Generated when a scrollbar's box has been moved
SCROLL_LINE_DOWN
Generated when a scrollbar's bottom or left endpoint (button)
is selected
SCROLL_LINE_UP
Generated when a scrollbar's top or right endpoint (button) is
selected
SCROLL_PAGE_DOWN
Generated when the scrollbar's field below (or to the left of)
the box is selected
SCROLL_PAGE_UP
Generated when the scrollbar's field above (or to the right of)
the box is selected
Component examples
Example:
Button Class
In this example, two Button objects are created and placed on a Frame. The Font and
Label are changed on the first Button , while the second one’s background is changed to
red. Text field is also placed on the frame
The WinClosing class is used to terminate the program if the window is closed.
import java.awt.*;
import java.awt.event.*;
public class CompTest extends Frame
{
Button playButton,pauseButton;
TextField tf;
public CompTest()
{
//two buttons are created several of their properties are
58
// changed using the appropriate set() method
playButton = new Button();
playButton.setFont(new Font("Serif", Font.BOLD,12));
playButton.setLabel("Play");
pauseButton = new Button("Disable");
pauseButton.setBackground(Color.red);
tf = new TextField(20);
tf.setText("this is some text");
setLayout(new FlowLayout());
add(pauseButton);
add(playButton);
add(tf);
addWindowListener(new WinClosing());
setBounds(100,100,400,120);
setVisible(true);
}
public static void main(String args[])
{
CompTest tb = new CompTest();
}
}
// The winclosing class closes terminates the program when the //window is closed
class WinClosing extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
Note: The setFont, setEnabled, and setBackground methods are Component classes.
Check Box
import java.awt.*;
import java.awt.event.*;
public class TestCheckbox extends Frame implements ItemListener
{
Checkbox cb;
TextField tf;
public TestCheckbox()
{
59
cb = new Checkbox("Bold");
cb.setFont(new Font("Serif", Font.BOLD,12));
cb.setState(true);
// The Checkbox is registered with an ItemListener. in this case //the frame acts as the
itemListener
cb.addItemListener(this);
tf = new TextField(15);
tf.setFont(new Font("Serif", Font.BOLD,12));
tf.setText("JavaJavaJava");
setLayout(new FlowLayout());
add(cb);
add(tf);
addWindowListener(new WinClosing());
setBounds(100,100,400,120);
setVisible(true);
}
// The itemStateChanged() method must be implemented by the
//ItemListener. Since the Frame is acting as the
//ItemListener in this example, the method is contained in the //TestCheckBox class
public void itemStateChanged(ItemEvent ie)
{
// The check box generates ItemEvent objects when its
// selected change changes. The checked state of the check box is determined. if the
// check box is currently selected, the font style is set to bold
// if unchecked , the style is et to plain
Checkbox cbox = (Checkbox) ie.getItemSelectable();
if (cbox.getState() == true)
{
tf.setFont(new Font("Serif", Font.BOLD,12));
}
else
{
tf.setFont(new Font("Serif", Font.PLAIN,12));
}
}
public static void main(String args[])
{
TestCheckbox tcb= new TestCheckbox();
}
}
60
// The winclosing class closes terminates the program when the // window is closed
class WinClosing extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
CheckBox Group class
import java.awt.*;
import java.awt.event.*;
public class TestCBG extends Frame implements ItemListener
{
Checkbox cb1,cb2,cb3;
CheckboxGroup cbg;
TextField tf;
public TestCBG()
{
// three check boxes are created They are assigned to a
instantiated.
// Initially, none of the checkbox objects are checked
//checkbox group when they are
cbg = new CheckboxGroup();
cb1= new Checkbox("London", cbg, false);
cb2= new Checkbox("Tokyo", cbg, false);
cb3= new Checkbox("Ottawa", cbg, false);
// The checkbox objects are registered with an ItemListener
// In this case the Frame acts as the ItemListener
cb1.addItemListener(this);
cb2.addItemListener(this);
cb3.addItemListener(this);
tf= new TextField(15);
tf.setEditable(false);
Panel p = new Panel();
p.add(cb1);
p.add(cb2);
p.add(cb3);
add(p, BorderLayout.CENTER);
add(tf, BorderLayout.SOUTH);
addWindowListener(new WinClosing());
setBounds(100,100,400,120);
61
setVisible(true);
}
// The itemStateChanged() method must be implemented by the
//ItemListener. Since the Frame is acting as the
//ItemListener in this example, the method is contained in the //TestCBG class
public void itemStateChanged(ItemEvent ie)
{
// The Text field is updated to reflect the currently //selected item
Checkbox cbox = (Checkbox) ie.getItemSelectable();
tf.setText("City selected is " + cbox.getLabel());
}
public static void main(String args[])
{
TestCBG tcbg= new TestCBG();
}
}
// The winclosing class closes terminates the program when the window is closed
class WinClosing extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
Choice class
import java.awt.*;
import java.awt.event.*;
public class TestChoice extends Frame implements ItemListener
{
Choice c;
TextField tf;
TestChoice()
{
// A choice object is created and four selections are addded to it
c = new Choice();
c.add("Fish");
c.add("Rice");
c.add("Beans");
c.add("Cheese");
c.select("Rice");
// The choice object is registered with an ItemListener
// In this case, the TestChoice class acts as the //ItemListener
62
c.addItemListener(this);
tf= new TextField(15);
tf.setEditable(false);
tf.setText("Food Selected is "+ c.getSelectedItem());
Panel p = new Panel();
p.add(c);
add(p, BorderLayout.CENTER);
add(tf, BorderLayout.SOUTH);
addWindowListener(new WinClosing());
setBounds(100,100,400,120);
setVisible(true);
}
// The itemStateChanged() method must be implemented by the
//ItemListener. Since the TestChoice class is acting as the
//ItemListener in this example, the method is contained in the //TestChoice class
public void itemStateChanged(ItemEvent ie)
{
// The Text field is updated to reflect the currently //selected item
Choice choice = (Choice) ie.getItemSelectable();
tf.setText("Food selected is " + choice.getSelectedItem());
}
public static void main(String args[])
{
TestChoice tc= new TestChoice();
}
}
// The winclosing class closes terminates the program when the //window is closed
class WinClosing extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
List class
import java.awt.*;
import java.awt.event.*;
public class TestList extends Frame implements ItemListener
{
63
List lst;
TextField tf;
TestList()
{
// A list object is created and four selections are added
lst = new List(5);
lst.add("Fish");
lst.add("Rice");
lst.add("Beans");
lst.add("Beans");
lst.setFont(new Font("Serif", Font.BOLD, 12));
// The List object is registred with an item listener
// in this case, the Test List class acts as the Item //listener
lst.addItemListener(this);
tf = new TextField(15);
tf.setEditable(false);
tf.setText("Food selected is "+ lst.getSelectedItem());
Panel p = new Panel();
p.add(lst);
add(p,BorderLayout.CENTER);
add(tf,BorderLayout.SOUTH);
addWindowListener(new WinClosing());
setBounds(100,100,400,120);
setVisible(true);
}
// The itemStateChanged() method must be implemented by the
//ItemListener. Since the Testlist class is acting as
// itemListener in this example, the method
// is contained in the TesttList class
public void itemStateChanged(ItemEvent ie)
{
// The Text Field is updated to reflect the currently //selected item
List l = (List) ie.getItemSelectable();
tf.setText("Food selected is "+ l.getSelectedItem());
}
public static void main(String args[])
64
{
TestList tlst= new TestList();
}
}
// The winclosing class closes terminates the program when the //window is closed
class WinClosing extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
Scrollbar class
import java.awt.*;
import java.awt.event.*;
public class TestScrollbar extends Frame implements AdjustmentListener
{
Scrollbar sb;
TextField tf;
TestScrollbar()
{
// a scrollar object is created and its properties set
sb = new Scrollbar(Scrollbar.VERTICAL);
sb.setMinimum(1);
sb.setMaximum(100);
sb.setValue(50);
sb.setUnitIncrement(10);
sb.setBlockIncrement(1);
sb.addAdjustmentListener(this);
tf = new TextField(3);
tf.setEditable(false);
tf.setText(" "+ sb.getValue());
Panel p = new Panel();
p.add(tf);
p.add(sb);
add(p);
65
addWindowListener(new WinClosing());
setBounds(100,100,400,120);
setVisible(true);
}
// Implement the adjustmentValueChanged method
public void adjustmentValueChanged(AdjustmentEvent ae)
{
// The Text Field is updated to reflect the value of the //scrollbar
tf.setText(""+ sb.getValue());
}
public static void main(String args[])
{
TestScrollbar tsb= new TestScrollbar();
}
}
// The winclosing class closes terminates the program when the //window is closed
class WinClosing extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
TextComponent Classes (TextField and TextArea)
(a) Using TextField
import java.awt.*;
import java.awt.event.*;
public class TestTextField extends Frame
{
TextField tf1,tf2;
TestTextField()
{
// to textfield objects are created, the first
// is made read only. The second uses as
// Echo character to replace whatever text is inserted
tf1 = new TextField("This text is read only", 20);
tf1.setFont(new Font("Serif",Font.PLAIN,12));
tf1.setEditable(false);
tf1.select(5,10);
tf2 = new TextField(10);
66
tf2.setEchoChar('*');
Panel p = new Panel();
p.add(tf1);
p.add(tf2);
add(p);
addWindowListener(new WinClosing());
setBounds(100,100,400,120);
setVisible(true);
}
public static void main(String args[])
{
TestTextField ttf = new TestTextField();
}
}
// The winclosing class closes terminates the program
// when the window is closed
class WinClosing extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
(b) Using TextArea class
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class TestA extends Frame implements TextListener
{
TextArea ta;
TextField tf;
Date date;
public TestA()
{
// A TextArea is created with 5 rows and 25 columns.
// A string is added to the TextArea.
//Another string is inserted at position 0,
// pushing the original string to the right
ta=new TextArea(5,25);
ta.append("Filling Santa's shelves ");
ta.insert("We are Santa's Elves \n",0);
// The TextArea object is registred with a text listener
// In this case, the TestA class acts as the Text listener
ta.addTextListener(this);
tf = new TextField(20);
67
tf.setEditable(false);
Panel p = new Panel();
p.add(ta);
add(p,BorderLayout.CENTER);
add(tf,BorderLayout.SOUTH);
addWindowListener(new WinClosing());
setBounds(100,100,400,200);
setVisible(true);
}
//The TextValueChanged() method must be implemented by the
//TextListener. Since the TestA class is acting as the Text //listener in this example, this method is
contained in the
// TestA class
public void textValueChanged(TextEvent te)
{
// if the contents of the text area are changed.
// the text field indicates when the i.e the time the
// TextArea was changed
date = new Date();
tf.setText("Text changed at "+date.toString());
}
public static void main(String args[])
{
TestA tta = new TestA();
}
}
// The winclosing class closes terminates the program
//when the window is closed
class WinClosing extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
68
Container Classes
(Dialog, FileDialog, Frame, Panel, ScrollPane,Window)
(a)
Using Dialog class
import java.awt.*;
import java.awt.event.*;
public class TestDialog extends Frame implements ActionListener
{
Button quitButton,yesButton,noButton;
Dialog d;
public TestDialog()
{
quitButton = new Button("quit");
quitButton.addActionListener(this);
setLayout(new FlowLayout());
add(quitButton);
createDialog();
addWindowListener(new WinClosing());
setBounds(150,150,200,200);
setVisible(true);
}
// CreateDialog() creates a dialog that confirms
//the quit command.// Dialog objects are always
//the child of a parent object. A reference
// to the parent object, in this case the
//TestDialog class is passed to the Dialog constructor
public void createDialog()
{
d = new Dialog(this);
d.setResizable(false);
yesButton = new Button("yes");
yesButton.addActionListener(this);
noButton = new Button("no");
noButton.addActionListener(this);
d.setLayout(new FlowLayout());
d.add(yesButton);
d.add(noButton);
d.setSize(200,100);
}
public void actionPerformed(ActionEvent ae)
{
// If the "quit" button is pressed, the confirm dialog
69
// is made visible. If the "yes" button in the dialog
// is pressed, the program terminates. If the "no" button
// in the dialog is pressed, the dialog is made invisible
if(ae.getActionCommand().equals("quit"))
{
d.show();
}
if(ae.getActionCommand().equals("yes"))
{
System.exit(0);
}
if(ae.getActionCommand().equals("no"))
{
d.setVisible(false);
}
}
public static void main(String args[])
{
TestDialog td = new TestDialog();
}
}
// The winclosing class closes terminates the program
// when the window is closed
class WinClosing extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
(b) Using FileDialog class
import java.awt.*;
import java.awt.event.*;
public class TestFD extends Frame
{
FileDialog fd;
TestFD()
{
addWindowListener(new WinClosing());
setBounds(100,100,400,400);
setVisible(true);
createFileDialog();
}
70
// CreateFileDialog() creates a FileDialog object that lists the
//contents of the current directory. The FileDialog object //remains visible until a file is selected
public void createFileDialog()
{
fd = new FileDialog(this, "Pick a file");
fd.show();
}
//getString method is used to return the name of the selected //file
public String getString()
{
return fd.getFile();
}
public static void main(String args[])
{
TestFD tfd = new TestFD();
System.out.println("File selected was "+ tfd.getString());
}
}
// The winclosing class closes terminates the program when the //window is closed
class WinClosing extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
(c)
Using Frame Class
import java.awt.*;
import java.awt.event.*;
public class TestFrame extends Frame
{
TestFrame()
{
addWindowListener(new WinClosing());
setTitle("Simple Frame");
setResizable(false);
setBounds(100,100,200,200);
setVisible(true);
}
public static void main(String args[])
{
71
TestFrame tf = new TestFrame();
}
}
// The winclosing class closes terminates the program when the window is closed
class WinClosing extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
(d) Using Panel Class
import java.awt.*;
import java.awt.event.*;
public class TestPanel extends Frame
{
Button b1,b2;
TestPanel()
{
b1 = new Button("button 1");
b2 = new Button("button 2");
Panel p = new Panel();
p.add(b1);
p.add(b2);
add(p);
addWindowListener(new WinClosing());
setBounds(100,100,200,120);
setVisible(true);
}
public static void main(String args[])
{
TestPanel tp = new TestPanel();
}
}
// The winclosing class closes terminates the program when the window is closed
class WinClosing extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
72
(e) Using ScrollPane class
import java.awt.*;
import java.awt.event.*;
public class TestSP extends Frame
{
ScrollPane sp;
TestSP()
{
sp = new ScrollPane();
Panel p = new Panel();
for (int i =0;i<10; ++i)
{
p.add(new Button("button" + i));
}
// The panel containing the Button objects is placed
// within a scroll pane and the ScrollPane is placed
// in the frame. The button objects must be placed in
// a panel first, because a ScrollPane can only contain one
//component
sp.add(p);
add(sp);
addWindowListener(new WinClosing());
setBounds(100,100,200,120);
setVisible(true);
}
public static void main(String args[])
{
TestSP tsp = new TestSP();
}
}
// The winclosing class closes terminates the program when the //window is closed
class WinClosing extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
(f) Using Window Class
import java.awt.*;
import java.awt.event.*;
public class TestWind extends Frame
73
{
TestWind()
{
addWindowListener(new WinClosing());
setBounds(100,100,250,250);
setVisible(true);
createWindow();
}
// The createWindow method creates and displays a Window object.
// Window objects are always the child of a parent object. a
// reference to the parent object, in this case the TestWind //class is passed to the Window
constructor
public void createWindow()
{
Window w = new Window(this);
w.setSize(100,100);
w.setBackground(Color.yellow);
w.add(new Label("James"));
w.show();
}
public static void main(String args[])
{
TestWind tw = new TestWind();
}
}
// The winclosing class closes terminates the program when the //window is closed
class WinClosing extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
Layout Managers Classes: (BorderLayout, CardLayout,FlowLayout,
GridLayout,etc)
(a)
Using BorderLayout class
import java.awt.*;
import java.awt.event.*;
public class TestBL extends Frame
{
74
Button northButton,eastButton,westButton,southButton;
Label nameLabel,secondLabel;
public TestBL()
{
northButton = new Button("north");
eastButton = new Button("east");
westButton = new Button("west");
southButton = new Button("south");
nameLabel = new Label("The Center");
secondLabel = new Label("Region");
// The button objects are placed in panels
//before being placed on the frame. if the
// buttons were placed on the borderlayout regions
//directly, they would be sized to fill the
// entire region. Placing them in panels
// maitains the preferred size of the Button
Panel pN= new Panel();
pN.add(northButton);
Panel pS= new Panel();
pS.add(southButton);
Panel pE= new Panel();
pE.add(eastButton);
Panel pW= new Panel();
pW.add(westButton);
Panel pC= new Panel();
pC.setBackground(Color.yellow);
pC.add(nameLabel);
pC.add(secondLabel);
add(pN,BorderLayout.NORTH);
add(pS,BorderLayout.SOUTH);
add(pE,BorderLayout.EAST);
add(pW,BorderLayout.WEST);
add(pC,BorderLayout.CENTER);
addWindowListener(new WinClosing());
setBounds(100,100,300,150);
setVisible(true);
}
public static void main(String args[])
{
TestBL tbl = new TestBL();
}
}
// The winclosing class closes terminates the program when the window is closed
75
class WinClosing extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
(b) Using CardLayout Class
import java.awt.*;
import java.awt.event.*;
public class TestCard extends Frame implements ActionListener
{
Button nextButton, prevButton,firstButton;
Panel centerPanel,southPanel;
String name;
CardLayout c1;
public TestCard()
{
c1 = new CardLayout();
nextButton = new Button("next");
prevButton = new Button("previous");
firstButton= new Button("first");
nextButton.addActionListener(this);
prevButton.addActionListener(this);
firstButton.addActionListener(this);
southPanel = new Panel();
southPanel.add(nextButton);
southPanel.add(prevButton);
southPanel.add(firstButton);
// 10 label objects are added to a panel using a
// card layout layout manager
centerPanel = new Panel();
centerPanel.setLayout(c1);
for (int i=0;i<10;++i)
{
name = "Label " + i;
centerPanel.add(new Label("Label " + i,Label.CENTER), name);
}
add(southPanel, BorderLayout.SOUTH);
add(centerPanel, BorderLayout.CENTER);
addWindowListener(new WinClosing());
76
setBounds(100,100,200,120);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
// depending on which button is pressed the
//CardLayout object calls the next(),
// previous() or first() methods
if(ae.getActionCommand().equals("next"))
{
c1.next(centerPanel);
}
if(ae.getActionCommand().equals("previous"))
{
c1.previous(centerPanel);
}
if(ae.getActionCommand().equals("first"))
{
c1.first(centerPanel);
}
}
public static void main(String args[])
{
TestCard tc = new TestCard();
}
}
// The winclosing class closes terminates the program
// when the window is closed
class WinClosing extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
(c) Using FlowLayout class
import java.awt.*;
import java.awt.event.*;
public class TestFL extends Frame
{
public TestFL()
{
//5 buttons are added to the Frame using a FlowLayout Layout Manager
77
setLayout(new FlowLayout(FlowLayout.CENTER));
for(int i=0;i<6; ++i)
{
add(new Button("button " + i));
}
addWindowListener(new WinClosing());
setBounds(100,100,300,120);
setVisible(true);
}
public static void main(String args[])
{
TestFL tfl = new TestFL();
}
}
//The winclosing class closes terminates the program when
//the window is closed
class WinClosing extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
(d) Using the GridLayout class
import java.awt.*;
import java.awt.event.*;
public class TestGL extends Frame
{
Button goButton;
Label nameLabel;
TextField nameTF;
public TestGL()
{
goButton = new Button("Go");
goButton.setFont(new Font("Times", Font.BOLD,14));
nameLabel = new Label("Name");
nameTF = new TextField(20);
// Setting the number of rows to 0 means the number of rows
//will be increased to match the number of components
//added to the layout
setLayout(new GridLayout(0,1));
78
Panel p1 = new Panel();
p1.add(nameLabel);
add(p1);
Panel p2 = new Panel();
p2.add(nameTF);
add(p2);
Panel p3 = new Panel();
p3.add(goButton);
add(p3);
addWindowListener(new WinClosing());
setBounds(100,100,200,200);
setVisible(true);
}
public static void main(String args[])
{
TestGL tgl = new TestGL();
}
}
// The winclosing class closes terminates the
// program when the window is closed
class WinClosing extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
Menu Classes: Menu. MenuBar, PopupMenu, etc
(a)
Using Menu and MenuBar classes
import java.awt.*;
import java.awt.event.*;
public class TestMenuBar extends Frame
{
MenuBar mb;
Menu helpMenu, fileMenu;
TestMenuBar()
{
// two Menu objects are created are created
// and placed on the menubar
helpMenu = new Menu("Help");
helpMenu.add("help");
79
fileMenu = new Menu("File");
fileMenu.add("Save");
mb = new MenuBar();
mb.add(fileMenu);
// one of the mnu objects is designated as the
// help menu and is placed at the far right of the
// MenuBar .It is not added to the MenuBar using add()
// in the normal way.
mb.setHelpMenu(helpMenu);
setMenuBar(mb);
addWindowListener(new WinClosing());
setBounds(100,100,200,120);
setVisible(true);
}
public static void main(String args[])
{
TestMenuBar tmb = new TestMenuBar();
}
}
// The winclosing class closes terminates the program
// when the window is closed
class WinClosing extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
Summary of AWT classes
Component class
It is the superclass of all containers and non-menu related components. Because it an
abstract class, a Component object is never created. The class contains general
purpose methods to manipulate, modify and return information about containers and
components
Some Component class methods:
(i) Methods to return the current state of a Component
hasfocus() - returns a true if the input focus is owned by the invoking component
IsDisplayable()- returns a true is the invoking component can be displayed
isEnabled() - returns a true if the invoking component can accept inputs and generate
events
isFocusTraversable() – Returns a true if the invoking component can accept the input
as focus. Focus is traversed from traversable components using the Tab or Shift_Tab
keyboard sequences
80
isOpaque()- returns a true if the invoking component is opaque, meaning that it hides
any features beneath it. AWT components are opaque.
IsShowing()– Returns a true if the invoking component’s state is valid. A valid
component is one that is correctly positioned and sized within its parent container and
all of its children are valid
IsVisible()- Returns a true if the invoking Component will be visible when the screen
is painted.
(ii)
Location Methods
getBounds() – Returns Rectangle object that encompasses the outer boundary of the
invoking component
getX() and getY() – return the x and y positions in pixels of the origin of the invoking
component
setBounds() – is a combination of the setLocation() and setSize() methods. It sets the
location and size of the invoking component.
setLocation()- Places the upper left hand corner of the invoking component at the
designated location.
(iii) Methods to retrieve component properties
getBackground() and getForeground() - return the Color object representing the
background and foreground Colour
getFont() – Returns the Font object associated with the invoking component
getName() – gets the name of the invoking component
getParent() – Returns the parent container of the invoking component
(iv)
Methods to set component properties
requestFocus() - attempts to bring focus to the invoking component. If the focus is not
focus traversable, the attempt will fail.
setBackground(Color backgroundColor) and setForeground(Color foregroundColor) set
the background and foreground of the invoking component
setFont(Font f) – Sets/Changes the font displayed by the invoking component
setEnabled(Boolean) – Enables or disables the invoking component.
setName(String name) – Sets the name associated with the invoking component
setVisible(Boolean) – Determines whether the invoking component is visible on the
screen or not.
transferFocus() - Moves the focus away from the invoking component to the next focus
traversable component
(v) Size methods
getHeight() and getWidth() return the current height and height of the invoking
component.
getMaximumSize(), getMinimumSize(), getPreferredSize() return the maximum,minimum
and preferred size as determined by the component’s peer classes.
setSize(int width, int height) – Changes the size, if possible of the invoking component to
the specified size.
81
getSize() returns a Dimension object containing the current width and height of the
invoking component.
Component Classes:
Button,CheckBox,CheckBox,Choice,Label,List,ScrollBar,TextArea,TextField
A component is a object that resides inside a container and is visible to the user. They
can be used to provide information, initiate some action or store data. Under this
section, A GUI component is defined as a subclass of Component that is not a
Container. GUI components placed inside a container make up a user interface.
GUI components have various properties associated with them:
(a) A component is either enables or disabled. Only enabled components can generate
events
(b) A component can be in or out of focus.. There can only be one components with focus
at any one time.
(c) A component is either visible or invisible
- Most containers are by default visible
- Most GUI components are by default invisible
(d) Every component has an internal name that is used by the program to identify the
component. The name is accessed by the getname() and setname() methods
(e) A component can have one or more pop up menus associated with it. The popup menus
contains menu items that are specific to the component
Button class
- Implements a button that can be clicked. The button is used to initiate an action.
Every button has an action command associated with it that can b used to identify the
button. A button object can generate an ActionEvent object when pressed.
Button () Constructors:
- Button()
- Button(String Label)
Action Command methods
- getActionCommand()
- setActionCommand(String actionCmmand)
Every button has an action command associated with it. These methods return or set the
action command for the invoking Button object. If no action is set, they return the Button
label. The getActionCommand() can also be used by the ActionListener interface to
determine which button has been selected.
Action Listener methods
AddActionListener(Action Listener al) and removeActionListener(Action Listener al) –
The methods register and remove the invoking Button object with/from the
ActionListener object
Label Methods
82
- getLabel(), setLabel(String label) return and set the label on the invoking Button object
respecitively.
Canvas class
A canvas is a rectangular drawing area
Canvas Constructors
- Canvas()
Canvas Methods
-
paint(Graphics g) – drawing something on the invoking object using the
methods provided in the Graphics class
Checkbox class
It is a box with a label that can be checked or unchecked, similar to an on/off switch. Two
or more checkboxes can be grouped together and become mutually exclusive by using a
CheckboxGroup object
Checkbox Constructors
Checkbox()
Checkbox(String label)
Checkbox(String label, boolean )
Checkbox(String label, Boolean, CheckboxGroup cg)
Checkbox(String label, CheckboxGroup cg, Boolean)
Note: Assigning the CheckGroup to null makes the checkbox initially independent.
Checkbox Label Methods
getLabel() and setLabel(String label) – returns and sets the label displayed by the
invoking Checkbox object.
Checked State methods
getState(), setState(Boolean) checks or unchecks the invoking Checkbox object and
return true if the invoking checkbox object is checked.
CheckboxGroup Methods
getCheckboxGroup(), set CheckboxGroup(Checkbox cbg)
ItemListener methods
-addItemListener()
-removeItemListener()
CheckBoxGroup constructor
-
CheckBoxGroup()
CheckboxGroup selection methods
83
- getSelectedCheckbox()
- setSelectedCheckBox(CheckBox cb)
toString() method – returns a String representation of the invoking CheckboxGroup
object.
Choice class
Constructor
- Choice()
Methods that add or remove elements
 add(),addItem(String item)
 insert(String item, int index)
 remove(String item), remove(index)
 removeAll()
getItemCount() returns the number of selectable items in the invoking Choice object
getItem(int index) returns the item at position index of the choice object
ItemListener methods
 addItemListener()
 removeListener()
Methods that select or return selected items
-
select(int index)
getSelectedItem()
getSelectedIndex()
Label Class
Constructors
- Label()
- Label(String s)
- Label(String s, int alignment)
Alignment constants
- Label.LEFT
-Label.RIGHT
- Label.CENTER
Alignment Methods
- getAlignment()
- setAlignment(int align)
Text Methods
-
getText()
setText()
List Class
Constructors
84
-
List()
List(int visibleRows)
List(int visibleRows, Boolean Multipleselections)
Action Listener methods
-addActionListener(), removeActionListener()
Methods that add or remove elements
-
add(String item)
replaceItem(String item, int index)
remove(String item), remove(int index)
removeAll()
getItemCount() – returns the number of items in the List Object
ItemListener methods
-
addItemListener(), removeItemListener()
Methods that return an element
-
getItem(int index)
getItems() returns all the items from the List object as a String array.
Selection methods
-getSelecteItem()
-getSelectedItems()
-getSelectedindex()
-getSelectedIndexes()
- selected(int index)
- deselect(int index)
-isIndexSelected(int index)
ScrollBar class
Constructors
-
ScrollBar()
ScrollBar(int orientation)
ScrollBar(int orientation, int value, int minimum, int maximum)
The value is initial value of the Scrollbar. The minimum and maximum are the range
of values the scrollbar can have. The visible quantity is the range of values
represented by the width of the slider. Note that the maximum value that the
Scrollbar can reach by moving the slider is equal to maximum – visible.
85
Orientation constants: Scrollbar. HORIZONTAL, Scrollbar. VERTICAL. If they
-
If they are not provided to the constructor , the orientatin is set to vertical and
the value,visible,minimum and maximum parameters are set to 0.
Adjustment Listener methods


AddAdjustmentListener (AdjustmentListener al
removeAdjustmentListener(AdjustmentListener al)
Appearance methods
- getVisibleAmount(),setVisibleAmount(int amount)
Orientation methods
- getOrientation()
- setOrientation(int orientation)
Range and Increment methods
- getBlockIncrement()
- getMaximum()
- getMinimum()
- setBlockIncrement()
- setMaximum(int max)
- setMinimum(int min)
- setUnitIncrement(int increment)
Methods that return or set the scrollbar
-getValue(), setValue(int value)
- setValues(int value, int visible,int minimum, int maximum)
TextArea class
Constructors
TextArea()
TextArea(int rows, int columns)
TextArea(String s)
TextArea(String s, int rows, int cols)
TextArea(String s, int rows, int cols, int scrollbarPolicy)
Scrollbar Policy constants
 TextArea.SCROLLBARS_BOTH
 TextArea.SCROLLBARS_HORIZONTAL_ONLY
 TextArea.SCROLLBARS_NONE
 TextArea.SCROLLBARS_VERTICAL_ONLY
Methods to add text
- append(String str)
-insert(String str, int pos)
-replaceRange(String str, int start, int end)
86
Sizing methods
-getRows()
-setRows(int rows)
-getColumns()
-setColumns(int cols)
TextComponent class
- This is the parent of both the TextArea and TextField class
Caret methods
Caret is the text cursor
- getCaretPosition()
- setCaretPosition(int pos)
Color methods
- getBackground()
- setBackground()
Editable Property methods
-isEditable()
- setEditable(Boolean editable)
Selection methods
- getSelectionStart()
- getSelectionEnd()
- select(int startindex, int end Index)
- selectAll()
- setSelectionStart(int startIndex)
- setSelectionEnd(int endIndex)
Text methods
-getText()
-setText()
getSelectedText()
Text Listener Methods
AddTextListener(), removeListener()
Text Field Class
TextField() Constructor
- TextField()
- TextField(int cols)
- TextField(String s)
- TextFied(String s, int cols)
ActionListener Methods
87
-addActionListner(ActionListener al), removeActionListener(ActionListener al)
Echo Character methods
- echoCharIsSet()
-getEchoChar()
-setEchoChar()
Sizing Methods
-getColumns()
-setColumns(int columns)
setText method
- setText(String Text)
88