001 Core 15 - Java Programming - III Sem
001 Core 15 - Java Programming - III Sem
SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
II INTRODUCING CLASSES 15
V INTRODUCTION OF AWT 58
Page 1 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
UNIT - I
PRIMITIVE DATA TYPES IN JAVA
To deal with numerical information, Java uses six predefined data types, called primitive
numerical data types. These are int, long, short, byte, float, and double, and they allow us to
represent integer and real numbers.
Java offers two additional non-numeric primitive data types: char (to represent
alphanumeric characters and special symbols) and Boolean (to represent the truth values true
and false).
We will describe these data types in Java by specifying for each of them:
The domain:
The set of possible values that can be represented in the memory of the computer by
means of the primitive data type (note that this set will always be finite);
Type int
Dimension 32 bit (4 byte)
Domain the set of integer numbers in the interval [−231, +231 − 1]
(more than 4 billion values)
Operations + sum
- difference
* product
/ integer division
rest of the integer division
Example:
Int a,b,c; // Declaration of variables of type int a = 1;
// Use of literals
B = 2;
C = a + b; // Arithmetic expression that involves operators of the language
Page 2 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
Example:
int I = 1; System.Out.Println(4);System.Out.Printin(i);System.Out.Println(i+4);
The symbol + can be used both for the sum of two numbers and to concatenate two
strings: "aaa" + "bbb" corresponds to "aaa"concat("bbb").
In the second statement, , “+” is applied to a string and an integer, and hence denotes
string concatenation. More precisely, the integer 4 is first converted to the string "4", and then
concatenated to the string "3". Hence, the argument "3"+4 of println() is of type string.
Both statements are correct, since the method println() is overloaded: the Java library
contains both a version that accepts an integer as parameter, and a version that accepts a
string as parameter.
Type byte
Dimension 8 bit (1 byte)
Domain the set of integer numbers in the interval [−27, +27 − 1] = [−128,
+127]
Operations + sum
- difference
* product
/ integer division
rest of the integer division
Page 3 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
least-used Java type, since it is defined as having its high byte first (called big-endian format).
Type short
Dimension 16 bit (2 byte)
Domain the set of integer numbers in the interval [−215, +215 − 1] = [−32768, +32767]
Operations + sum
- difference
* product
/ integer division
rest of the integer division
Example:
short a, b, c; // Declaration of variables of type short
a = 11300; // Use of literals
b = Short.parseShort ("22605"); // Conversion from String to short c = b a;
// Arithmetic expression
Type long
Dimension 64 bit (8 byte)
Domain the set of integer numbers in the interval [−263, +263
− 1]
Operations + sum
- difference
* product
/ integer division
rest of the integer division
Page 4 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
Type double
Dimension 64 bit (8 byte)
Domain set of 264 positive Minimum absolute value 1.79769313486231570 ·
and 10−308
negative real Maximum absolute value 2.250738585072014 · 10+308
numbers Precision ∼ 15 decimal digits
Operations + sum
- difference
* product
/ division
Literals sequences of digits with decimal dot optionally ending with a d (or D)
denoting values of the domain (e.g., 3.14 or 3.14d)
representation in scientific notation (e.g., 314E-2 or 314E-2d)
Example:
double pi, p2; // Declaration of variables of type double pi = 3.14;
// Use of literals
p2 = 628E-2d; // Use of literals
p2 = pi * 2; // Arithmetic expression
Primitive data types for real numbers: float
Type float
Dimension 32 bit (4 byte)
Domain set of 232 positive and Minimum absolute value 1.4012985 · 10−38
negative real numbers Maximum absolute value 3.4028235 · 10+38
Precision ∼ 7 decimal digits
Operations + sum
- difference
* product
/ division
Literals sequences of digits with decimal dot ending with an f (or F)
denoting values of the domain (e.g., 3.14f)
representation in scientific notation (e.g., 314E-2f)
Example:
float pi, a, b; // Declaration of variables of type float pi = 3.14f; // Use of
literals
a = 314E-2F // Use of literals
a++; // Use of increment operator (equivalent to: a = a + 1.0d;)
Example:
The following code fragment
double d = 98d; System.out.println("d = " + d); float x = 0.0032f; System.out.println("x = " + x);
Page 5 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
Semantics:
Converts the type of an expression to another type in such a way that operations
involving incompatible types become possible
Example:
int a = (int) 3.75; // cast to int of the expression 3.75 (of type double)
System.out.println(a); // prints 3
When we perform a cast, the result could be affected by a loss of precision: in the
previous example, the value 3.75 is truncated to 3.
Example:
double d; float f; long l; int i; short s; byte b;
// The following assignments are correct
d = f; f = l; l = i; i = s; s = b;
// The following assignments are NOT correct f = d; l = f; i = l; s = i; b = s;
// The following assignments are correct,
// but the result could be affected by a loss of precision
f = (float)d; l = (long)f; i = (int)l; s = (short)i; b = (byte)s;
Literals of type char can be denoted in various ways; the simplest one is through single quotes.
Example:
char c = ’A’; char c = ’0’;
Page 6 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
Conversion from int to char, which corresponds to obtain a character from its Unicode code:
Type boolean
Dimensio 1 bit
n
Domain the two truth values true and false
Operatio && and Note: in a && b, the value of b is computed only if a
ns is true
|| or Note: in a || b, the value of b is computed only if a
is false
! not
Literals true and false
Example:
boolean a,b,c,d,e; a = true;
b = false;
c = a && b; // c = a and b
d = a || b; // d = a or b
e = !a; // e = not a
System.out.println(e); // prints a string representing a boolean value,
// in this case the string "false" is printed
Page 7 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
Example:
Consider the following code fragment:
double r = Math.sqrt(2); // computes the square root of 2 double d = (r * r) - 2;
System.out.println(d); // prints 4.440892098500626E-16 instead of 0 boolean b = (d == 0);
System.out.println(b); // prints false (we would expect true)
Literals
A Java literal is a syntactic element (i.e. something you find in the source code of a Java
program) that represents a value. Examples are 1, 0.333F, false, 'X' and "Hello
world\n".
Since Java 7 it has been possible to use one or more underscores (_) for separating
groups of digits in a primitive number literal to improve their readability.
Version ≥ Java SE 7
int i1 = 123456;
int i2 = 123_456;
System.out.println(i1
== i2); // true
Boolean literals
Boolean literals are the simplest of the literals in the Java programming language. The
two possible boolean values are represented by the literals true and false. These are case -
sensitive.
For example:
Page 8 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
Zero or more other characters that are neither a double-quoteor a line-break character.
(A backslash (\) character alters the meaning of subsequent characters; see Escape
sequences in literals.)
A closing double-quote character
For example:
Character literals:
Character literals provide the most convenient way to express char values in Java source
code.
For example:
char a = 'a';
char doubleQuote = '"';
char singleQuote = '\'';
C
o
m
p
i
l
a
t
i
o
n
e
r
r
o
r
i
n Page 9 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
You need to be careful with leading zeros. A leading zero causes an integer literal to be
interpreted as octal not decimal.
Integer literals are unsigned. If you see something like -10 or +10, these are actually
expressions using the unary - and unary + operators.
The range of integer literals of this form has an intrinsic type of int, and must fall in the
range zero to 231 or 2,147,483,648.
Note that 231 is 1 greater than Integer. MAX_VALUE. Literals from 0 through to
2147483647 can be used anywhere, but it is a compilation error to use 2147483648
without a preceding unary - operator. (In other words, it is reserved for expressing the value of
Integer. MIN_VALUE.)
Note that the distinction between int and long literals is significant in other places. For
example
Page 10 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
int i =
147483647; // Produces a negative value because the
long l = i + 1; operation is
// prmed using 32 bit arithmetic, and the
// addition overflows
long l2 = i + // Produces the (intuitively) correct
1L; value.
Arrays
You create arrays when you want to operate on a collection of variables of the same
data type or pass them all around together. An array is essentially a collection of elements of
the same data type. The elements are also called components of the array. Each element of the
array is accessed using a unique index value, also called a subscript. For example, an array of
integers contains several elements, each of type int, and an array of floating-point numbers
contains several elements, each of type float. Because array elements are accessed using a
single variable name coupled with a subscript, you do not need to create several unique
variable names in your program code to store and access many variables having the same data
type.
Declaring Arrays
The general syntax for declaring an array is as follows:
type array Name [ ];
Java allows another syntax for array declaration, as follows:
Creating Arrays
Now that you know how to declare an array variable, the next task is to allocate space
for the array elements. To allocate space, you use new keyword.
For example, to create an array of 10 integers, you would use the following code:
int[] numbers; numbers = new int[10];
The first statement declares a variable called numbers of the array type, with each
element of type int. The second statement allocates contiguous memory for holding 10 integers
and assigns the memory address of the first element to the variable numbers. An array
initializer provides initial values for all its components. You may assign different values to these
Page 11 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
There are two techniques for initializing the array elements. The elements of the array
may be initialized at runtime via value assignment, or initialized via array literals.
Initializing at runtime
An array element may be initialized at runtime using its index value. Consider the
following declaration for an array of integers:
int[] numbers = new int[10]:
Each element may now be initialized to a desired value by using a block of code such as
the following:
numbers[0] = 10; numbers[1] = 5; numbers[2] = 145;
... numbers[9] = 24;
Initialize all the elements of the array to the same value, any one of the looping
statement can be used. For example, the following for loop will initialize all the elements of the
preceding array to zero:
for (int i = 0; i < 10; i++) {
numbers[i] = 0; }
Multidimensional Arrays
Multidimensional arrays, as the name suggests, contain more than one dimension. You
can create two-dimensional, three-dimensional, and n-dimensional arrays in Java (where n is
any natural number). The number of dimensions may be any large number, subject to the
restrictions imposed by the compiler. The JDK compiler puts this limit at 255, which is so large
that developers need not worry about it.
Page 12 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
The type specifies the type of data that each array element will hold. The array Name
specifies the name for the array. The two square brackets indicate that the current array
variable declaration refers to a two-dimensional array.
Suppose you have to write a program to store marks obtained by each student in a class
in various subjects. Let’s assume that each student takes five subjects and that 50 students are
in the class. You will need to create a two-dimensional array to store this data.
You would write the following block of code to create such an array:
final int NUMBER_OF_SUBJECTS = 5; final int NUMBER_OF_STUDENTS = 50;
int[][] marks;
marks = new int[NUMBER_OF_SUBJECTS][NUMBER_OF_STUDENTS];
The first dimension of the array (that is, the row) specifies the subject ID, and the second
dimension (that is, the column) specifies the student ID. You could easily interchange rows and
columns in the preceding declaration by changing their order of declaration as shown in the
following statement:
marks = new int[NUMBER_OF_STUDENTS][NUMBER_OF_SUBJECTS];
In this case, the first dimension specifies the student ID and the second dimension
specifies the subject ID.
Page 13 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
Page 14 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
UNIT - II
INTRODUCING CLASSES
Class Fundamentals
Thus, a class is a template for an object, and an object is an instance of a class. Because
an object is an instance of a class, you will often see the two words object and instance used
interchangeably.
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}}
The data, or variables, defined within a class are called instance variables. The code is
contained within methods. Collectively, the methods and variables defined within a class are
called members of the class. In most classes, the instance variables are acted upon and
accessed by the methods defined for that class. Thus, it is the methods that determine how a
class’ data can be used.
Variables defined within a class are called instance variables because each instance of
the class (that is, each object of the class) contains its own copy of these variables.
Thus, the data for one object is separate and unique from the data for another.
Declaring a Class :
The following code snippet shows a declaration for the Point class.
class Point {
int x; int y;
}
The class is defined using the keyword class followed by its name, Point. The modifier
field is optional and is not applied in this definition. The modifier defines the class visibility, and
the possible values for this modifier. The body of the class is enclosed in braces. The body of
this class consists only of fields. Contains two fields, x and y, of type int. This simple Point class
definition does not contain any methods
Page 15 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
Declaring Objects
A class definition serves as a template from which you create objects for the use of your
application code. For example, by using our class definition of Point, can create several Point
objects. Each Point object will be characterized by two distinct fields, x and y, which specify the
x-coordinate and y-coordinate of the point, respectively. Each Point object will have its own
copy of the data members x and y. These members are called instance variables of an object
because they belong to a particular instance of the class. The process of creating an object from
a class definition is called class instantiation. We say that a class has been instantiated when we
create an object.
Accessing/Modifying Fields
Accessing the fields declared in the preceding example is simple. To access the x-
coordinate of the point p, you use the syntax p.x, and to access the y-coordinate, you use the
syntax p.y. The general form for accessing a field is object Reference. fieldName. With respect
to our example, objectReference is p and fieldname is y or x.
class TestPoint {
Page 16 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
Point p (4, 5)
You might think that b2 is being assigned a reference to a copy of the object referred to
by b1. That is, you might think that b1 and b2 refer to separate and distinct objects. However,
this would be wrong. Instead, after this fragment executes, b1 and b2 will both refer to the
same object. The assignment of b1 to b2 did not allocate any memory or copy any part of the
original object. It simply makes b2 refer to the same object as does b1. Thus, any changes made
to the object through b2 will affect the object to which b1 is referring, since they are the same
object.
Although b1 and b2 both refer to the same object, they are not linked in any other way.
For example, a subsequent assignment to b1 will simply unhook b1 from the original object
without affecting the object or affecting b2.
For example:
Box b1 = new Box(); Box b2 = b1;
b1 = null;
Here, b1 has been set to null, but b2 still points to the original object.
Declaring Methods
The purpose of adding a method to the class definition is to provide some functionality
to it. The functionality we are going to add to Point class involves determining the distance of
the point from the origin. In the following example a method called getDistance() that returns
the distance between the point and the origin.
import java.util.*;
class Point {
int x; int y;
double getDistance() {
return (Math.sqrt(x * x + y * y));
}
}
Page 17 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
class TestPoint {
Page 18 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
int square()
{
return 10 * 10;
}
While this method does, indeed, return the value of 10 squared, its use is very limited.
However, if you modify the method so that it takes a parameter, as shown next, then you can
make square( ) much more useful.
int square(int i)
{
return i * i;
}
Now, square( ) will return the square of whatever value it is called with. That is, square(
) is now a general-purpose method that can compute the square of any integer value, rather
than just 10.
Here is an example:
int x, y;
x = square(5); // x equals 25 x = square(9); // x equals 81 y = 2;
x = square(y); // x equals 4
In the first call to square( ), the value 5 will be passed into parameter i. In the second
call, i will receive the value 9. The third invocation passes the value of y, which is 2 in this
example. As these examples show, square( ) is able to return the square of whatever data it is
passed.
Understanding static
Normally a class member must be accessed only in conjunction with an object of its
class. However, it is possible to create a member that can be used by itself, without reference
to a specific instance. To create such a member, precede its declaration with the keyword
static. When a member is declared static, it can be accessed before any objects of its class are
created, and without reference to any object. You can declare both methods and variables to
be static. The most common example of a static member is main( ). main( ) is declared as static
because it must be called before any objects exist.
Instance variables declared as static are, essentially, global variables. When objects of
its class are declared, no copy of a static variable is made. Instead, all instances of the class
share the same static variable.
Page 19 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
example shows a class that has a static method, some static variables, and a static initialization
block:
Introducing final
A variable can be declared as final. Doing so prevents its contents from being modified.
This means that you must initialize a final variable when it is declared. (In this usage, final is
similar to const in C/C++/C#.)
For example:
final int FILE_NEW = 1; final int FILE_OPEN = 2; final int FILE_SAVE = 3; final int FILE_SAVEAS = 4;
final int FILE_QUIT = 5;
Subsequent parts of your program can now use FILE_OPEN, etc., as if they were
constants, without fear that a value has been changed.
It is a common coding convention to choose all uppercase identifiers for final variables.
Variables declared as final do not occupy memory on a per-instance basis. Thus, a final variable
is essentially a constant.
The keyword final can also be applied to methods, but its meaning is substantially
different than when it is applied to variables.
Page 20 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
Sometimes you will want to pass information into a program when you run it. This is
accomplished by passing command-line arguments to main( ). A command-line argument is the
information that directly follows the program’s name on the command line when it is executed.
To access the command-line arguments inside a Java program is quite easy—they are stored as
strings in the String array passed to main( ). For example, the following program displays all of
the command-line arguments that it is called with:
// Display all command-line arguments. class CommandLine {
public static void main(String args[]) { for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " +
args[i]);
}
}
Try executing this program, as shown here: java CommandLine this is a test 100 -1
INHERITANCE
Why Inheritance?
The major advantage of inheritance is code reuse. You will be able to use your tested
code in your new applications, with desired additions, without really touching it. Even if the
code has been distributed, you are able to add more functionality to your new applications
without breaking the distributed code.
For example, to develop a payroll system, you could define classes such as Person,
Employee, Staff, Manager, Director, and so on, that perfectly fit into an inheritance hierarchy.
Because such classes have a lot of commonality, putting them in an inheritance hierarchy will
make your code more maintainable in the future.
What Is Inheritance?
All of us have observed inheritance in nature. For example, a baby inherits the
characteristics of her parents, a child plant inherits the characteristics of its parent plant, and so
on. We attempt to bring this feature into our software by inheriting the characteristics of the
existing classes and then extending their functionality. To identify the classes, which have some
commonality and thus are probable candidates for creating inheritance hierarchies, object-
oriented analysis techniques provide some rules.
Let me illustrate inheritance with a concrete real-life example. Suppose we are asked to
write some assets management software. Now, what are the classifications of assets a person
may possess? A person might have a bank account, a few investments in securities, and a home
in which to live. There may be many more types of assets, We would like to represent these
assets in our software, so let’s start creating classes to represent them. The first thing that
comes to mind is an Asset class, which is a common term for all the assets previously
mentioned. We represent the Asset class.
Page 21 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
Page 22 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
Using super
super has two general forms. The first calls the superclass’ constructor. The second is
used to access a member of the superclass that has been hidden by a member of a subclass.
Each use is examined here
// initialize width, height, and depth using super() BoxWeight(double w, double h, double d,
double m) {
super(w, h, d); // call superclass constructor weight = m;
}}
Here, BoxWeight( ) calls super( ) with the parameters w, h, and d. This causes the Box( )
constructor to be called, which initializes width, height, and depth using these values.
BoxWeight no longer initializes these values itself. It only needs to initialize the value unique to
it: weight. This leaves Box free to make these values private if desired.
Page 23 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
subOb.show();
}}
This program displays the following: i in superclass: 1 i in subclass: 2
Although the instance variable i in B hides the i in A, super allows access to the i defined
in the superclass. As you will see, super can also be used to call methods that are hidden by a
subclass.
Page 24 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
Page 25 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
In a class hierarchy, when a method in a subclass has the same name and type signature
as a method in its superclass, then the method in the subclass is said to override the method in
the superclass. When an overridden method is called from within a subclass, it will always refer
to the version of that method defined by the subclass. The version of the method defined by
the super class will be hidden.
Page 26 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
}
void show() {
super.show(); // this calls A's show() System.out.println("k: " + k);
}}
If you substitute this version of A into the previous program, you will see the following output:
i and j: 1 2
k: 3
Here, super.show( ) calls the superclass version of show( ).
Method overriding occurs only when the names and the type signatures of the two methods
are identical. If they are not, then the two methods are simply overloaded. For example,
consider this modified version of the preceding example:
// Methods with differing type signatures are overloaded – not
// overridden. class A {
int i, j;
A(int a, int b) { i = a;
j = b;
}
// display i and j void show() {
System.out.println("i and j: " + i + " " + j);
}}
// Create a subclass by extending class A. class B extends A {
int k;
Page 27 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
UNIT - III
PACKAGES AND INTERFACES
Packages
Packages are used in Java in order to prevent naming conflicts, to control access, to
make searching/locating and usage of classes, interfaces, enumerations and annotations easier,
etc.
A Package can be defined as a grouping of related types (classes, interfaces,
enumerations and annotations) providing access protection and namespace management.
Some of the existing packages in Java are:
java.lang − bundles the fundamental classes
java.io − classes for input , output functions are bundled in this package
Programmers can define their own packages to bundle group of classes/interfaces, etc.
It is a good practice to group related classes implemented by you so that a programmer can
easily determine that the classes, interfaces, enumerations, and annotations are related.
Since the package creates a new namespace there won't be any name conflicts with
names in other packages. Using packages, it is easier to provide access control and it is also
easier to locate the related classes.
Creating a Package
While creating a package, you should choose a name for the package and include
a package statement along with that name at the top of every source file that contains the
classes, interfaces, enumerations, and annotation types that you want to include in the
package.
The package statement should be the first line in the source file. There can be only one
package statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and
annotation types will be placed in the current default package.
To compile the Java programs with package statements, you have to use -d option as shown
below.
interface Animal {
Page 28 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
Now, let us implement the above interface in the same package animals −
package animals;
System.out.println("Mammal eats");
}
public void travel() {
System.out.println("Mammal travels");
return 0;
m.eat();
m.travel();
}}
$ javac -d . Animal.java
$ javac -d . MammalInt.java
Now a package/folder with the name animals will be created in the current directory and these
class files will be placed in it as shown below.
Page 29 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
You can execute the class file within the package and get the result as shown below.
Mammal eats
Mammal travels
package payroll;
e.mailCheck();
What happens if the Employee class is not in the payroll package? The Boss class must
then use one of the following techniques for referring to a class in a different package.
The fully qualified name of the class can be used. For example −
payroll.Employee
The package can be imported using the import keyword and the wild card (*). For example −
import payroll.*;
The class itself can be imported using the import keyword. For example −
import payroll.Employee;
Page 30 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
Access Protection
Classes and packages are both means of encapsulating and containing the name space
and scope of variables and methods. Packages act as containers for classes and other
subordinate packages. Classes act as containers for data and code. The class is Java’s smallest
unit of abstraction. Because of the interplay between classes and packages, Java addresses four
categories of visibility for class members:
Subclasses in the same package
Non-subclasses in the same package
Subclass in different package
Classes that are neither in the same package nor subclasses
The three accesses specify, private, public, and protected, provide a variety of ways to
produce the many levels of access required by these categories.
Importing Packages:
Java includes the import statement to bring certain classes, or entire packages, into
visibility. Once imported, a class can be referred to directly, using only its name. The import
statement is a convenience to the programmer and is not technically needed to write a
complete Java program. If you are going to refer to a few dozen classes in your application,
however, the import statement will save a lot of typing.
In a Java source file, import statements occur immediately following the package
statement (if it exists) and before any class definitions. This is the general form of the import
statement:
import pkg1[.pkg2].(classname|*);
Here, pkg1 is the name of a top-level package, and pkg2 is the name of asubordinate
THE LANGUAGE
package inside the outer package separated by a dot (.). There is practical limit on the depth of
a package hierarchy, except that imposed by the file system. Finally, you specify either an
explicit classname or a star (*), which indicates that the Java compiler should import the entire
package. This code fragment shows both forms in use:
Page 31 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
Interface
An interface is a reference type in Java. It is similar to class. It is a collection of abstract
methods. A class implements an interface, thereby inheriting the abstract methods of the
interface.
Along with abstract methods, an interface may also contain constants, default methods,
static methods, and nested types. Method bodies exist only for default methods and static
methods.
Writing an interface is similar to writing a class. But a class describes the attributes and
behaviors of an object. And an interface contains behaviors that a class implements.
Unless the class that implements the interface is abstract, all the methods of the
interface need to be defined in the class.
Declaring Interfaces
The interface keyword is used to declare an interface. Here is a simple example to
declare an interface:
Example
Following is an example of an interface:
import java.lang.*;
Page 32 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
Example
/* File name : Animal.java */
interface Animal {
Implementing Interfaces
When a class implements an interface, you can think of the class as signing a contract,
agreeing to perform the specific behaviors of the interface. If a class does not perform all the
behaviors of the interface, the class must declare itself as abstract.
A class uses the implements keyword to implement an interface. The implements
keyword appears in the class declaration following the extends portion of the declaration.
Example
System.out.println("Mammal eats");
System.out.println("Mammal travels");
return 0;
Page 33 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
m.eat();
m.travel();
}}
Tagging Interfaces
The most common use of extending interfaces occurs when the parent interface does
not contain any methods. For example, the MouseListener interface in the java.awt.event
package extended java.util.EventListener, which is defined as:
Example
package java.util;
Page 34 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
{}
An interface with no methods in it is referred to as a tagging interface. There are two basic
design purposes of tagging interfaces −
Exception Handling
The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.
Page 35 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
executed. If we perform exception handling, the rest of the statement will be executed. That is
why we use exception handling in Java.
1. Checked Exception
The classes which directly inherit Throwable class except Run time Exception and Error
are known as checked exceptions e.g. IOException, SQLException etc. Checked exceptions are
checked at compile-time.
Page 36 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
2. Unchecked Exception
The classes which inherit Run time Exception are known as unchecked exceptions e.g.
Arithmetic Exception, Null Pointer Exception, Array Index Out of Bounds Exception etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
3. Error
Error is irrecoverable e.g. Out Of Memory Error, Virtual Machine Error, Assertion Error
etc.
Keyword Description
try The "try" keyword is used to specify a block where we should place exception code.
The try block must be followed by either catch or finally. It means, we can't use try
block alone.
catch The "catch" block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block
later.
finally The "finally" block is used to execute the important code of the program. It is
executed whether an exception is handled or not.
throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception.
It specifies that there may occur an exception in the method. It is always used with
method signature.
Page 37 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
}
} catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index out-of-bounds: "
+ e);
}
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to provide
the exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as Null Pointer Exception, it is programmers fault that he is not
performing check up before the code being used.
Page 38 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
11. n();
12. }catch(Exception e){System.out.println("exception handled");}
13. }
14. public static void main(String args[]){
15. Testthrows1 obj=new Testthrows1();
16. obj.p();
17. System.out.println("normal flow...");
18. } }
normal flow...
Page 39 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
Multithreaded Programming:
Multithreading in java is a process of executing multiple threads simultaneously. A
thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking. However, we use multithreading than
multiprocessing because threads use a shared memory area. They don't allocate separate
memory area so saves memory, and context-switching between the threads takes less time
than process.
Thread Priorities
Java assigns to each thread a priority that determines how that thread should be
treated with respect to the others. Thread priorities are integers that specify the relative
priority of one thread to another. As an absolute value, a priority is meaningless; a higher-
priority thread doesn’t run any faster than a lower-priority thread if it is the only thread
running. Instead, a thread’s priority is used to decide when to switch from one running thread
to the next. This is called a context switch.
Page 40 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
The rules that determine when a context switch takes place are simple:
A thread can voluntarily relinquish control. This is done by explicitly yielding, sleeping, or
blocking on pending I/O. In this scenario, all other threads are examined, and the
highest-priority thread that is ready to run is given the CPU.
A thread can be preempted by a higher-priority thread. In this case, a lower-priority
thread that does not yield the processor is simply preempted—no matter what it is
doing—by a higher-priority thread. Basically, as soon as a higher-priority thread wants
to run, it does. This is called preemptive multitasking.
In cases where two threads with the same priority are competing for CPU cycles, the
situation is a bit complicated. For operating systems such as Windows 98, threads of equal
priority are time-sliced automatically in round-robin fashion. For other types of operating
systems, threads of equal priority must voluntarily yield control to their peers. If they don’t, the
other threads will not run.
Although the main thread is created automatically when your program is started, it can
be controlled through a Thread object. To do so, you must obtain a reference to it by calling the
method currentThread( ), which is a public static member of Thread.
Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread. Thread class extends Object class and implements Runnable interface.
Page 41 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. Runnable interface have only one method named run().
start() method of Thread class is used to start a newly created thread. It performs following
tasks:
Page 42 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
UNIT – IV
APPLETS & EVENT HANDLING
Applets are small java programs that can be transported over the internet from one
computer to another and run using the Applet viewer or any web browser that supports java.
All applets are subclasses of Applet. Thus, all applets must import java.applet. Applets must
also import java.awt. (AWT stands for the Abstract Window Toolkit) Since all applets run in a
window, it is necessary to include support for that window.
Applet extends the AWT class Panel. In turn, Panel extends Container, which extends
Component. These classes provide support for Java's window-based, graphical interface.
Thus, Applet provides all of the necessary support for window-based activities.
Applets override a set of methods by which the browser or applet viewer interfaces to
the applet and controls its execution.
Four of these methods—init( ), start( ), stop( ), and destroy( )—are defined by Applet.
Another, paint( ), is defined by the AWT Component class.
When an applet begins, the AWT calls the following methods, in this sequence:
init( ) start( ) paint( )
When an applet is terminated, the following sequence of method calls takes place:
stop( ) destroy( )
init( )
The init( ) method is the first method to be called. This is where you should initialize
variables. This method is called only once during the run time of your applet.
start( )
The start( ) method is called after init( ). It is also called to restart an applet after it has
been stopped. Whereas init( ) is called once—the first time an applet is loaded:
Start( )is called each time an applet's HTML document iss displayed onscreen. So, if a user
leaves a web page and comes back, the applet resumes execution at start( ).
Page 43 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
paint( )
The paint( ) method is called each time your applet's output must be redrawn. the
applet window may be minimized and then restored. paint( ) is also called when the applet
begins execution. Whatever the cause, whenever the applet must redraw its output, paint( ) is
called.
The paint( ) method has one parameter of type Graphics. This parameter will contain
the graphics context, which describes the graphics environment in which the applet is running.
This context is used whenever output to the applet is required.
stop( )
The stop( ) method is called when a web browser leaves the HTML document
containing the applet—when it goes to another page.
destroy( )
The destroy( ) method is called when the environment determines that your applet
needs to be removed completely from memory. At this point, you should free up any resources
the applet may be using. The stop( ) method is always called before destroy( ).
repaint() method
Whenever our applet needs to update the information displayed in its window, we can
call the repaint( ) method which calls the paint() method.
The repaint of methods have four forms:
1. void repaint()
This causes the entire window to be repainted.
2. void repaint(int left,int top,int width,int height)
This version specifies a region that will be repainted. Here the dimentions are specified
in regions. If you need to repaint a small portion of the window, its more efficient.
3. Void repaint(long maxDelay)
4. Void repaint(long maxDelay ,int x, int y, int width, int height)
Multiple request for repainting that occur within a short time that can be collapsed by
the AWT. To avoid this situation, specifies the maximum number of milliseconds that can be
elapse before update() is called. Here maxDelay specifies the maximum number of milliseconds.
import java.awt.*;
import java.applet.*;
/*<applet code="SimpleBanner" width=300 height=50>
Page 44 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
</applet>*/
public class SimpleBanner extends Applet implements Runnable
{ String msg = " A Simple Moving Banner.";
Thread t = null;
int state;
boolean stopFlag;
public void init()
{ setBackground(Color.cyan);
setForeground(Color.red);
}
public void start()
{ t = new Thread(this);
stopFlag = false;
t.start();
}
public void run()
{ char ch;
for( ; ; ) {
try { repaint(); Thread.sleep(250);
ch = msg.charAt(0);
msg = msg.substring(1, msg.length()); msg += ch;
if(stopFlag)
break;
} catch(InterruptedException e) {}
} }
public void stop()
{ stopFlag = true;
t = null;
}
public void paint(Graphics g)
{ g.drawString(msg, 50, 30);
}}
Page 45 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
Page 46 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
CODE :
CODE is a required attribute that gives the name of the file containing your applet‘s
scompiled .class file.
ALT:
The ALT tag is an optional attribute used to specify a short text message that should be
displayed if the browser understands the APPLET tag but can't currently run Java applets.
NAME:
NAME is an optional attribute used to specify a name for the applet instance. Applets
must be named in order for other applets on the same page to find them by name and
communicate with them.
Page 47 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
ALIGN :
ALIGN is an optional attribute that specifies the alignment of the applet. LEFT, RIGHT,
TOP,BOTTOM, MIDDLE
getDocumentBase( )
Returns the directory holding the HTML file that started the applet
getCodeBase( )
Returns directory from which the applet's class file was loaded
Loading an Image
To load an image use the the getImage( ) method
defined by the Applet class. It has the following forms:
Image getImage(URL url)
returns an Image object that encapsulates the image found at the location specified by url.
Image getImage(URL url, String imageName)
returns an Image object that encapsulates the image found at the location specified by url and
having the name specified by imageName.
Displaying an Image
We can display an image by using drawImage( ), which is a member of the Graphics class.
Syntax:
boolean drawImage(Image imgObj, int left, int top, ImageObserver imgOb). This displays
the image passed in imgObj with its upper-left corner specified by left and top. imgOb is a
reference to a class that implements the Image Observer interface
/* <applet code="Load" width=248 height=146>
</applet>*/
import java.awt.*; import java.net.URL;
import java.applet.*;
public class Load extends Applet
{ Image img;
public void init()
{ URL u=null;
try{ u=new URL("file:/c:/s3mca21/viv.jpg");
}catch(MalformedURLException e){System.out.println(e);}
Page 48 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
img = getImage(u);
}
public void paint(Graphics g)
{ g.drawImage(img, 0, 0, this);
}
}
Playing Audio Files using Applet
Create an audioclip object by using the getAudioClip() method defined in the Applet class .
syntax.
AudioClip getAudioClip(URL url)
AudioClip getAudioClip(URL url,String clipName)
Then play the AudioClip object using the Play() method of the AudioClip class .
Also we can stop the audioclip by using the stop method of the AudioClip class
Drawing Lines
Void drawLine(int startX, int startY, int endX, int endY)
Draw a line that begins at startX,startY and ends at endX,endY.
Drawing Rectangles
The drawRect( ) and fillRect( ) methods display an outlined and filled rectangle,respectively.
void drawRect(int top, int left, int width, int height)
void fillRect(int top, int left, int width, int height)
To draw a rounded rectangle, use drawRoundRect( ) or fillRoundRect( ),
void drawRoundRect(int top, int left, int width, int height,
int xDiam, int yDiam)
void fillRoundRect(int top, int left, int width, int height,
int xDiam, int yDiam)
A rounded rectangle has rounded corners. The upper-left corner of the rectangle is top,left. The
dimensions of the rectangle are specified by width and height. The diameterof the rounding arc
along the X axis is specified by xDiam. The diameter of the rounding arc along the Y axis is
specified by yDiam.
Page 49 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
Drawing Arcs
Arcs can be drawn with drawArc( ) and fillArc( )
void drawArc(int top, int left, int width, int height, int startAngle,int sweepAngle)
void fillArc(int top, int left, int width, int height, int startAngle,int sweepAngle)
The arc is bounded by the rectangle whose upper-left corner is specified by top,left and whose
width and height are specified by width and height. The arc is drawn from startAngle through
the angular distance specified by sweepAngle.
Drawing Polygons
It is possible to draw arbitrarily shaped figures using drawPolygon( ) and fillPolygon( )
void drawPolygon(int x[ ], int y[ ], int numPoints)
void fillPolygon(int x[ ], int y[ ], int numPoints)
The polygon's endpoints are specified by the coordinate pairs contained within the x
and y arrays. The number of points defined by x and y is specified by numPoints.
Color Methods
The Color class defines several methods that help manipulate colors. They are
examined here Using Hue, Saturation, and Brightness.
The hue-saturation-brightness (HSB) color model is an alternative to red-green-blue
(RGB) for specifying particular colors. Figuratively, hue is a wheel of color. The hue is specified
with a number between 0.0 and 1.0
Page 50 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
Fonts have a family name, a logical font name, and a face name. The family name is the
general name of the font, such as Courier. The logical name specifies a name, such as
Monospaced, that is linked to an actual font at runtime. The face name specifies a specific font,
such as Courier Italic.
Fonts are encapsulated by the Font class. Several of the methods defined by Font are listed.
Page 51 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
boolean is Plain( ) : Returns true if the font includes the PLAIN style value.
Otherwise, false is returned.
String to String( ) : Returns the string equivalent of the invoking font.
Determining the Available Fonts
When working with fonts, often you need to know which fonts are available on your
machine. To obtain this information, you can use the getAvailableFontFamilyNames( ) method
defined by the GraphicsEnvironment class. It is shown here:
String[ ] getAvailableFontFamilyNames( )
This method returns an array of strings that contains the names of the available font
families.
In addition, the getAllFonts( ) method is defined by the GraphicsEnvironment class. It is
shown here:
Font[ ] getAllFonts( )
This method returns an array of Font objects for all of the available fonts. Since these
methods are members of GraphicsEnvironment, you need a GraphicsEnvironment reference to
call them. You can obtain this reference by using the getLocalGraphicsEnvironment( ) static
method, which is defined by GraphicsEnvironment. It is shown here:
static GraphicsEnvironment getLocalGraphicsEnvironment( )
Here is an applet that shows how to obtain the names of the available font families:
// Display Fonts /*
<applet code="ShowFonts" width=550 height=60> </applet>
*/
import java.applet.*; import java.awt.*;
public class ShowFonts extends Applet {
public void paint(Graphics g) {
String msg = ""; String FontList[];
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
FontList = ge.getAvailableFontFamilyNames();
for(int i = 0; i < FontList.length; i++)
msg += FontList[i] + " ";
g.drawString(msg, 4, 16);
}}
Creating and Selecting a Font
To create a new font, construct a Font object that describes that font.
One Font constructor has this general form:
Font(String fontName, int fontStyle, int pointSize)
Page 52 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
Here, fontName specifies the name of the desired font. The name can be specified using either
the logical or face name. All Java environments will support the following fonts: Dialog,
DialogInput, SansSerif, Serif, and Monospaced. Dialog is the font used by your system’s dialog
boxes. Dialog is also the default if you don’t explicitly set a font. You can also use any other
fonts supported by your particular environment, but be careful—these other fonts may not be
universally available.
The style of the font is specified by fontStyle. It may consist of one or more of these
three constants: Font.PLAIN, Font.BOLD, and Font.ITALIC. To combine styles, OR them
together. For example, Font.BOLD | Font.ITALIC specifies a bold, italics style.
The size, in points, of the font is specified by point Size.
To use a font that you have created, you must select it using setFont( ), which is defined
by Component. It has this general form:
void setFont(Font fontObj)
Here, fontObj is the object that contains the desired font.
Obtaining Font Information
Suppose you want to obtain information about the currently selected font. To do this,
you must first get the current font by calling get Font( ). This method is defined by
the Graphics class, as shown here:
Font getFont( )
Once you have obtained the currently selected font, you can retrieve information about
it using various methods defined by Font.
EVENT HANDLING
Event is an object that specifies the change of state in the source. It is generated
whenever an action takes place like a mouse button is clicked or text is modified. when action
takes place an event is generated. The generated event and all the information about it such as
time of its occurrence, type of event etc, are sent to the appropriate event handling code
provided within the program.
Event Handling
It is based on the concept of source and listener.
Event source:
Event source is an object that generates a particular kind of event. An event is
generated when the internal state of an event source is changed.
Event Listener:
Event listener is an object which receives notification when an event occurs. The source
generates an event and sends it to one or more listeners. On receiving the event, listener
processes the event and returns it. The source has a registered list of listeners which will
receive the events as they occur. Only the listeners that have been registered actually receive
the notification when a specific event is generated.
Page 53 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
Event Handling
Java provides various classes and interfaces to handle the generated events
Event classes
1. import java.awt.*;
2. public class ButtonExample {
3. public static void main(String[] args) {
4. Frame f=new Frame("Button Example");
5. Button b=new Button("Click Here");
6. b.setBounds(50,100,80,30);
7. f.add(b);
8. f.setSize(400,400);
9. f.setLayout(null);
10. f.setVisible(true);
11. }
12. }
Event classes encapsulate all types of events occuring in the system. The supercalss of
all these event is the Event Object class. Event Object class belongs to java. util package.
Event Listener interfaces
The Action Listener Interface
When an Action Event occurs the action Performed() method defined by the Action
listener interface is invoked .The general form of the action Performed method is void action
Performed(Action Event e) e is the reference to an object of Action Event class.
When an Adjustment Event occurs the adjustment Value Changed() method defined by
the Adjustment listener interface is invoked
Page 54 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
Void keyTyped(KeyEvent e)
If a key B is pressed and released three events are generated. When a key is pressed, a
KEY_PRESSED event is generated. This results in a call to the keyPressed( ) event handler. When
the key is released, a KEY_RELEASED event is generated and the keyReleased( ) handler is
executed. If a character is generated by the keystroke, then a KEY_TYPED event is sent and the
keyTyped( ) handler is invoked.
There is one other requirement that your program must meet before it can process
keyboard events: it must request input focus. To do this, call request Focus( ), which is
defined by Component. If you don't, then your program will not receive any keyboard events.
Page 55 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
Page 56 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
bsub.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{ int x=Integer.parseInt(t1.getText());
int y=Integer.parseInt(t2.getText());
if (e.getSource()==bsub)
t3.setText(x-y+"");
else t3.setText(x+y+"");
}}
Page 57 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
UNIT - V
INTRODUCTION OF AWT
Container
The Container is a component in AWT that can contain another components
like buttons, textfields, labels etc. The classes that extends Container class are known as
container such as Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must use frame,
dialog or another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have
other components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have
other components like button, textfield etc.
Page 58 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
Example
import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
public static void main(String args[]){
First f=new First();
}}
The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above example
that sets the position of the awt button.
Page 59 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
import java.awt.*;
class MenuExample
{
MenuExample(){
Frame f= new Frame("Menu and MenuItem Example");
MenuBar mb=new MenuBar();
Menu menu=new Menu("Menu");
Menu submenu=new Menu("Sub Menu");
MenuItem i1=new MenuItem("Item 1");
MenuItem i2=new MenuItem("Item 2");
MenuItem i3=new MenuItem("Item 3");
MenuItem i4=new MenuItem("Item 4");
MenuItem i5=new MenuItem("Item 5");
menu.add(i1);
menu.add(i2);
menu.add(i3);
submenu.add(i4);
submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}
}
Output:
Page 60 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21
Page 61 of 61