0% found this document useful (0 votes)
22 views

001 Core 15 - Java Programming - III Sem

Uploaded by

ox maja
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

001 Core 15 - Java Programming - III Sem

Uploaded by

ox maja
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

STUDY MATERIAL FOR B.

SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21

UNIT CONTENT PAGE Nr

I PRIMITIVE DATA TYPES IN JAVA 02

II INTRODUCING CLASSES 15

III PACKAGES AND INTERFACES 28

IV APPLETS & EVENT HANDLING 43

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

The set of operations:


Operators of the programming language that allow us to perform elementary
operations on values of the primitive data type (e.g., +, -, /, *, etc.)
The set of literals: symbols of the language that define values of the primitive data type
(e.g., 10, 3.14, ’A’, true, etc.)
Moreover, we will specify the size of the memory occupied by a value of a certain data
type, which will be significant for the numeric data types.

The data type int:


The most commonly used integer type is int. It is a signed 32-bit type that has a range
from –2,147,483,648 to 2,147,483,647. In addition to other uses, variables of type int are
commonly employed to control loops and to index arrays.

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

Literals sequences of digits denoting values of the domain (e.g., 275930)

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

Writing of numbers of type int


To write a number of type int, we can directly use the print() or println() methods:

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").

Note the difference between the following two statements:


System.out.println(3 + 4); // prints 7 (as int); + denotes sum System.out.println("3" +
4); // prints 34 (as String), since the integer 4 is
// first converted to a String; + denotes concat
In the first statement, “+” is applied to two integers, and hence denotes the addition
operator. Hence, the argument 3+4 of println() is of type int.

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.

Other primitive data types for integer numbers: byte


The smallest integer type is byte. This is a signed 8-bit type that has a range from – 128
to 127. Variables of type byte are especially useful when you’re working with a stream of data
from a network or file.

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

Literals sequences of digits denoting values of the domain (e.g., 47)


Example:
byte a, b, c; // Declaration of variables of type byte
a = 1; // Use of literals
b = Byte. phrase Byte("47"); // Conversion from String to byte c = a - b;
// Arithmetic expression

Other primitive data types for integer numbers: short


Short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the

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

Literals sequences of digits denoting values of the domain (e.g., 22700)

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

Other primitive data types for integer numbers: long


Long is a signed 64-bit type and is useful for those occasions where an int type is not
large enough to hold the desired value. The range of a long is quite large. This makes it useful
when big, whole numbers are needed.

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

Literals sequences of digits ending with an l (or L)


denoting values of the domain (e.g., 9000000000L)
Example:
long a, b, c; // Declaration of variables of type long a = 9000000000L;
// Use of literals b = Long.parseLong("9000000000l");
// Conversion from String to long c = b / 300000L

Primitive data types for real numbers: double


In Java there are two primitive data types for representing real numbers. Due to the way
in which real numbers are represented internally in memory, these numbers are also called
floating point numbers. The data type for floating point numbers that is used by default in the
Java mathematical library is double.

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

Writing of numbers of type double or float


To write a number of type double or float, we can directly use the print() or println()
methods:

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

prints on the screen


d = 9.8E1 x = 3.2E-3

Explicit type conversion (casting):


If we want to compile and execute the wrong assignment statements in the previous
table, we have to insert an explicit type conversion (also called type cast).

Syntax: (type) expression


 type is the name of a type
 expression is an expression whose type will be forced to type

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;

The primitive data type char


Strings are constituted by single characters, which are values of type char. A variable of
type char can contain just a single character. The domain of the type char is constituted by the
more than 64000 characters of the Unicode standard. The Unicode standard establishes a
correspondence between numbers and symbols that can be either alphabetical, numerical, or
special symbols in various languages (including the Asiatic ones). For example, the character ’A’
corresponds to the numeric code 65., the character ’B’ to the numeric code 66, etc. For more
details on the Unicode standard, you can consult the website http://www.unicode.org/.

Literals of type char can be denoted in various ways; the simplest one is through single quotes.

Example:
char c = ’A’; char c = ’0’;

Operations that involve values of type char


Conversion from char to int, which corresponds to calculating the Unicode code of a character:
char c = ’A’;

Page 6 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21

int i = c; // i contains the Unicode code of the character ’A’


System.out.println(i); // prints 65

Conversion from int to char, which corresponds to obtain a character from its Unicode code:

int i = 65; // Unicode code of the character ’A’ char c = (char) i;


System.out.println(c); // prints ’A’

Conversion from char to String:


char c = ’A’;
String s = String.valueOf(c);
String s1 = Character.toString(c); // is equivalent to the previous statement

Extraction of a char from an object of type String:


String s = "hello";
char c = s.charAt(0); // extracts the character in position 0 from "hello",
// i.e., ’h’, and assigns it to the variable c
Reading a char:
String s = JOptionPane.showInputDialog("Insert a character"); char c = s.charAt(0);
Writing a char:

char c = ’a’; System.out.println(c);

The primitive data type Boolean


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

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

Comparing floating point numbers


A consequence of the rounding errors when representing or performing operations on
floating point numbers is that the comparison between such numbers could produce
unexpected results.

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, &#39;X&#39; 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.

For instance, these two declarations are equivalent:

Version ≥ Java SE 7
int i1 = 123456;
int i2 = 123_456;
System.out.println(i1
== i2); // true

This can be applied to all primitive number literals as shown below:


Version ≥ Java SE 7
byte color = 1_2_3;
short yearsAnnoDomini= 2_016;
int socialSecurtyNumber = 999_99_9999;
long creditCardNumber = 1234_5678_9012_3456L;
float piFourDecimals = 3.14_15F;
double piTenDecimals = 3.14_15_92_65_35;

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:

boolean flag = // using the 'true'


true; literal
flag = false; // using the 'false'
literal
String literals
String literals provide the most convenient way to represent string values in Java source
code. A String literal consists of:
 An opening double-quote (") character.

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:

"Hello world" // A literal denoting an 11 character String


"" // A literal denoting an empty (zero length) String
"\"" // A literal denoting a String consisting of one
// double quote character
"1\t2\t3\n" // Another literal with escape sequences

Character literals:
Character literals provide the most convenient way to express char values in Java source
code.

A character literal consists of:


 An opening single-quote (') character.
 A representation of a character. This representation cannot be a single-quote or a line-
break character, but it can be an escape sequence introduced by a backslash (\)
character; see Escape sequences in literals.
 A closing single-quote (') character.

For example:
char a = 'a';
char doubleQuote = '"';
char singleQuote = '\'';

A line-break in a character literal is a compilation error:

char newline = '


/
/

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

Decimal Integer literals


Integer literals provide values that can be used where you need a byte, short, int, long
or char instance. (This example focuses on the simple decimal forms. Other examples explain
how to literals in octal, hexadecimal and binary, and the use of underscores to improve
readability.)

Ordinary integer literals


The simplest and most common form of integer literal is a decimal integer literal. For
example:

0 // The decimal number (type


zero 'int')

1 // The decimal number one (type 'int')


42 // The decimal number forty two (type 'int')

You need to be careful with leading zeros. A leading zero causes an integer literal to be
interpreted as octal not decimal.

This literal actually means 7 x 8 + 7 ... or 63 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.)

Long integer literals


Literals of type long are expressed by adding an L suffix. For example:

2147483648L // The value of Integer.MAX_VALUE + 1


long big = 2147483648; // ERROR
long big2 = 2147483648L; // OK

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:

type[ ] array Name;


The square brackets in this syntax are also called the indexing operator because they
specify the index of an element in an array. The type specifies the type of element that the
array is going to store. The arrayName specifies the name by which the elements of the array
are addressed in the program code. Note that like in many other languages, the declaration
does not allow you to specify the size of the array.
To declare an array of integers, you would use the following declaration: int[] numbers;
The name of the array in this declaration is numbers. Thus, each element of the array
would be accessed using this name along with an appropriate index value.
To declare an array of float, use the following declaration:
Float[] Float Numbers:
The name of the array is float Numbers, and each element of the array holds a floating-
point number.

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

variables somewhere in your code, as explained in the next section.

To create an array of 20 floating-point numbers, use the following code fragment:


float[] floatNumbers; floatNumbers = new float[20];
The first statement declares a variable called floatNumbers of the array type. Each
element of the array is of the floating-point type. The second statement allocates space for
holding 20 floating-point-type elements and assigns the address of the first element to the
array variable.
Initializing Arrays:
At this point, you have learned how to declare an array, allocate the space for its
elements, and access its elements. Now you will learn to initialize the entire array to a desired
state before its elements are used.

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.

Let’s first discuss two-dimensional arrays.


Two-dimensional Arrays
A two-dimensional array can be visualized as a table consisting of rows and columns.
Each cell of the table denotes an array element.

The general syntax for declaring a two-dimensional array is as follows:


typearrayName [ ] [ ] ;
type[ ] [ ] arrayName ;

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.

The General Form of a Class


A class is declared by use of the class keyword. The classes that have been used up to
this point are actually very limited examples of its complete form. Classes can (and usually do)
get much more complex. The general form of a class definition is shown here:
class classname {
type instance-variable1; type instance-variable2;
// ...
type instance-variableN;

type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method

}
// ...
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.

To create an object, we use the following declaration:


Point p = new Point();
We use the new keyword to instantiate a class. We specify the class name after the new
keyword, followed by opening and closing parentheses. The opening and closing parentheses
indicate a method call—a call to a class constructor.

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.

The Class Example Program


We’ll now write a Java program to declare a Point class, instantiate it, and use it in the
application. Listing 3-1 gives the full program for declaring and using a Point class.

The Class Example Program


class Point {
int x; int y;
}

class TestPoint {

public static void main(String[] args) {


System.out.println("Creating a Point object ... ");
Point p = new Point();
System.out.println("Initializing data members ...");
p.x = 4;
p.y = 5;
System.out.println("Printing object");
System.out.println("Point p (" + p.x + ", " + p.y + ")");
}
}
The program output is shown here:
C:\360\ch03>java TestPoint Creating a Point object ...
Initializing data members ...
Printing object

Page 16 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21

Point p (4, 5)

Assigning Object Reference


Object reference variables act differently than you might expect when an assignment
takes place. For example

Box b1 = new Box(); Box b2 = b1;

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.

This situation is depicted here:

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 {

public static void main(String[] args) {


System.out.println("Creating a Point object ... ");
Point p1 = new Point();
System.out.println("Initializing object ...");
p1.x = 3; p1.y = 4;
double distance = p1.getDistance();
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb, Locale.US); formatter.format("Distance of
Point p1(" + p1.x + "," + p1.y
+ ") from origin is %.02f", distance);
System.out.println(sb);
System.out.println(); sb.delete(0, sb.length());
System.out.println("Creating another Point object ... ");
Point p2 = new Point();
System.out.println("Initializing object ...");
p2.x = 8; p2.y = 9;
distance = p2.getDistance();
formatter.format("Distance of Point p2(" + p2.x + "," + p2.y + ") from origin is %.02f",
distance);
System.out.println(sb);
}}
When we compile and run this program, we see the following output:
C:\360\ch03>java TestPoint Creating a Point object ...
Initializing object ...
Distance of Point p1(3,4) from origin is 5.00
Creating another Point object ...
Initializing object ...
Distance of Point p2(8,9) from origin is 12.04
The Point class now has a method added to its definition. The method getDistance
computes the point’s distance from the origin and returns a double value to the caller:
double getDistance() {
return (Math.sqrt(x * x + y * y)); }
The distance is computed using the sqrt method of the built-in Math class.
In the main method of the TestPoint class,an instance p1 shoud be created first of the Point
class and then initialize its data members. Next, call the getDistance method to determine the
point’s distance from the origin: double distance = p1.getDistance();
A method can be invoked by using the syntax object Reference. Method Name. Here, object
Reference is the reference to the Point object (that is, p1) and method Name is get Distance

Adding a Method That Takes Parameters


While some methods don’t need parameters, most do. Parameters allow a method to
be generalized. That is, a parameterized method can operate on a variety of data and/or be
used in a number of slightly different situations. To illustrate this point, let’s use a very simple
example. Here is a method that returns the square of the number 10:

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.

Methods declared as static have several restrictions:


 They can only call other static methods.
 They must only access static data.
 They cannot refer to this or super in any way.
If you need to do computation in order to initialize your static variables, you can declare a
static block which gets executed exactly once, when the class is first loaded. The following

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:

// Demonstrate static variables, methods, and blocks. class UseStatic {


static int a = 3; static int b;

static void meth(int x) { System.out.println("x = " + x); System.out.println("a = " + a);


System.out.println("b = " + b);
}
static {
System.out.println("Static block initialized."); b = a * 4;
}

public static void main(String args[]) { meth(42);


}
}
As soon as the UseStatic class is loaded, all of the static statements are run. First, a is set
to 3, then the static block executes (printing a message), and finally, b is initialized to a * 4 or
12. Then main( ) is called, which calls meth( ), passing 42 to x.
The three println( ) statements refer to the two static variables a and b, as well as to the
local variable x.

It is illegal to refer to any instance variables inside of a static method.

Here is the output of the program:


Static block initialized. x = 42
a=3
b = 12

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.

Using Command-Line Arguments

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

When you do, you will see the following output:


args[0]: this args[1]: is args[2]: a args[3]: test args[4]: 100
args[5]: -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.

Program Snippet to Demonstrate Sub classing


class Asset {
private int id; private String type;

Page 21 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21

public int getId() { return id;


}
public void setId(int id) { this.id = id;
}
public String getType() { return type;
}

public void setType(String type) { this.type = type;


}
public void printDescription() {
System.out.println("Asset ID: " + id);
System.out.println("Asset type: " + type);
}}
class BankAccount extends Asset {

private String bankName; private int accountNumber; private float balance;

public int getAccountNumber() { return accountNumber;


}
public void setAccountNumber(int accountNumber) { this.accountNumber =
accountNumber;
}
public float getBalance()
{ return balance;
}

public void setBalance(float balance) { this.balance = balance;


}
public String getBankName() { return bankName;
}

public void setBankName(String bankName) {


this.bankName = bankName;
}
public void printDescription() { super.printDescription();
System.out.println("Name: " + bankName);
System.out.printf("Account #: %d%n", accountNumber);
System.out.printf("Current balance: $%.02f%n", balance);
}}
Note that the BankAccount class definition does not contain any of the fields defined in
the Asset class. These characteristics (fields and methods) are automatically made available to
an object of BankAccount type. Note that the id and type fields of the Asset class are declared
private. As stated earlier, private fields are not visible to the code outside the class definition.
Therefore, to access these private fields, we create getter/setter methods for each field. These
methods are declared public and can be called from the code outside the current class
definition. To initialize these fields, we can use class constructors.

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

Using super to Call Superclass Constructors


A subclass can call a constructor method defined by its superclass by use of the
following form of super:
super(parameter-list);
Here, parameter-list specifies any parameters needed by the constructor in the superclass.
super( ) must always be the first statement executed inside a subclass’ constructor.
To see how super( ) is used, consider this
// BoxWeight now uses super to initialize its Box attributes. class BoxWeight extends Box {
double weight; // weight of box

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

A Second Use for super


The second form of super acts somewhat like this, except that it always refers to the
superclass of the subclass in which it is used.

This usage has the following general form:


super.member
Here, member can be either a method or an instance variable.
This second form of super is most applicable to situations in which member names of a subclass
hide members by the same name in the superclass. Consider this simple class hierarchy:
// Using super to overcome name hiding. class A {
int i;
}

// Create a subclass by extending class A. class B extends A {


int i; // this i hides the i in A

B(int a, int b) { super.i = a; // i in A i = b; // i in B


}
void show() {
System.out.println("i in superclass: " + super.i); System.out.println("i in subclass: " + i);
}}
class UseSuper {
public static void main(String args[]) { B subOb = new B(1, 2);

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.

Creating Multilevel Hierachy


Up to this point, we have been using simple class hierarchies that consist of only a
superclass and a subclass. However, you can build hierarchies that contain as many layers of
inheritance as you like. As mentioned, it is perfectly acceptable to use a subclass as a superclass
of another. For example, given three classes called A, B and C, C can be a subclass of B, which is
a subclass of A. Each subclass inherits all of the traits found in all of its superclasses. In this case,
C inherits all aspects of B and A. To see how a multilevel hierarchy can be useful, consider the
following program. In it, the subclass BoxWeight is used as a superclass to create the subclass
called Shipment. Shipment inherits all of the traits of BoxWeight and Box, and adds a field
called cost, which holds the cost of shipping such a parcel.
// Extend BoxWeight to include shipping costs.

// Start with Box. class Box {


private double width; private double height; private double depth;

// construct clone of an object


Box(Box ob) { // pass object to constructor width = ob.width;
height = ob.height; depth = ob.depth;
}

// constructor used when all dimensions specified Box(double w, double h, double d) {


width = w; height = h;
depth = d;
}
// constructor used when no dimensions specified Box() {
width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box
}
// constructor used when cube is created Box(double len) {
width = height = depth = len;
}
// compute and return volume double volume() {
return width * height * depth;
}}
// Add weight.
class BoxWeight extends Box { double weight; // weight of box

// construct clone of an object


BoxWeight(BoxWeight ob) { // pass object to constructor super(ob);
weight = ob.weight;
}

Page 24 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21

// constructor when all parameters are specified BoxWeight(double w, double h, double d,


double m) {
super(w, h, d); // call superclass constructor weight = m;
}

// default constructor BoxWeight() {


super(); weight = -1;
}

THE JAVA LANGUAGE


// constructor used when cube is created BoxWeight(double len, double m) {
super(len); weight = m;
}}
// Add shipping costs
class Shipment extends BoxWeight { double cost;

// construct clone of an object


Shipment(Shipment ob) { // pass object to constructor super(ob);
cost = ob.cost;
}

// constructor when all parameters are specified Shipment(double w, double h, double d,


double m, double c) {
super(w, h, d, m); // call superclass constructor cost = c;
}
// default constructor Shipment() {
super(); cost = -1; }
// constructor used when cube is created Shipment(double len, double m, double c) {
super(len, m); cost = c;
}}
class DemoShipment {
public static void main(String args[]) { Shipment shipment1 =new Shipment(10, 20, 15, 10, 3.41);
shipment shipment2 =new Shipment(2, 3, 4, 0.76, 1.28);
double vol;

vol = shipment1.volume(); System.out.println("Volume of shipment1 is " + vol);


System.out.println("Weight of shipment1 is "
+ shipment1.weight); System.out.println("Shipping cost: $" +
shipment1.cost); System.out.println();

vol = shipment2.volume(); System.out.println("Volume of shipment2 is " + vol);


System.out.println("Weight of shipment2 is "
+ shipment2.weight); System.out.println("Shipping cost: $" +
shipment2.cost);
}}
The output of this program is shown here:
Volume of shipment1 is 3000.0
Weight of shipment1 is 10.0 S

Page 25 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21

Shipping cost: $3.41

Volume of shipment2 is 24.0


Weight of shipment2 is 0.76
Shipping cost: $1.28

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.

Consider the following:


// Method overriding. class A {
int i, j;
A(int a, int b) { i = a;
j = b;
}
// display i and j void show() {
System.out.println("i and j: " + i + " " + j);
}}
class B extends A {

THE JAVA LANGUAGE


int k;

B(int a, int b, int c) { super(a, b);


k = c;
}

// display k – this overrides show() in A void show() {


System.out.println("k: " + k);
}}
class Override {
public static void main(String args[]) { B subOb = new B(1, 2, 3);

subOb.show(); // this calls show() in B


}}
The output produced by this program is shown here: k: 3
When show( ) is invoked on an object of type B, the version of show( ) defined within B
is used. That is, the version of show( ) inside B overrides the version declared in A.
If you wish to access the superclass version of an overridden function, you can do so by
using super
For example, in this version of B, the superclass version of show( ) is invoked within the
subclass’ version. This allows all instance variables to be displayed.
class B extends A { int k;
B(int a, int b, int c) { super(a, b);
k = c;

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;

B(int a, int b, int c) { super(a, b);


k = c;
THE JAVA LANGUAGE

// overload show() void show(String msg) {


System.out.println(msg + k);
}}
class Override {
public static void main(String args[]) { B subOb = new B(1, 2, 3);

subOb.show("This is k: "); // this calls show() in B subOb.show(); // this calls show() in A


}}
The output produced by this program is shown here: This is k: 3 i and j: 1 2
The version of show( ) in B takes a string parameter. This makes its type signature different
from the one in A, which takes no parameters. Therefore, no overriding (or name hiding) takes
place.

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.

javac -d Destination_folder file_name.java


Then a folder with the given package name is created in the specified destination, and
the compiled class files will be placed in that folder.
Example
Let us look at an example that creates a package called animals. It is a good practice to
use names of packages with lower case letters to avoid any conflicts with the names of classes
and interfaces.
Following package example contains interface named animals −

/* File name : Animal.java */


package animals;

interface Animal {

Page 28 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21

public void eat();


public void travel();

Now, let us implement the above interface in the same package animals −

package animals;

/* File name : MammalInt.java */

public class MammalInt implements Animal {

public void eat() {

System.out.println("Mammal eats");

}
public void travel() {

System.out.println("Mammal travels");

public int noOfLegs() {

return 0;

public static void main(String args[]) {

MammalInt m = new MammalInt();

m.eat();

m.travel();

}}

Now compile the java files as shown below:

$ 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

The import Keyword


If a class wants to use another class in the same package, the package name need not be
used. Classes in the same package find each other without any special syntax.
Example
Here, a class named Boss is added to the payroll package that already contains
Employee. The Boss can then refer to the Employee class without using the payroll prefix, as
demonstrated by the following Boss class.

package payroll;

public class Boss {

public void payEmployee(Employee e) {

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

Set CLASSPATH System Variable


To display the current CLASSPATH variable, use the following commands in Windows and UNIX
(Bourne shell):
 In Windows → C:\> set CLASSPATH
 In UNIX → % echo $CLASSPATH

To delete the current contents of the CLASSPATH variable, use:


 In Windows → C:\> set CLASSPATH =
 In UNIX → % unset CLASSPATH; export CLASSPATH

To set the CLASSPATH variable:


 In Windows → set CLASSPATH = C:\users\jack\java\classes
 In UNIX → % CLASSPATH = /home/jack/java/classes; export CLASSPATH

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:

import java.util.Date; import java.io.*;

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.

An interface is similar to a class in the following ways:


 An interface can contain any number of methods.
 An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.
 The byte code of an interface appears in a .class file.
 Interfaces appear in packages, and their corresponding bytecode file must be in a
directory structure that matches the package name.
 However, an interface is different from a class in several ways, including −
 You cannot instantiate an interface.
 An interface does not contain any constructors.
 All of the methods in an interface are abstract.
 An interface cannot contain instance fields. The only fields that can appear in an
interface must be declared both static and final.
 An interface is not extended by a class; it is implemented by a class.
 An interface can extend multiple interfaces.

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:

/* File name : NameOfInterface.java */

import java.lang.*;

// Any number of import statements

public interface NameOfInterface {

Page 32 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21

// Any number of final, static fields

// Any number of abstract method declarations\

Interfaces have the following properties:


 An interface is implicitly abstract. You do not need to use the abstract keyword while
declaring an interface.
 Each method in an interface is also implicitly abstract, so the abstract keyword is not
needed.
 Methods in an interface are implicitly public.

Example
/* File name : Animal.java */

interface Animal {

public void eat();

public void travel();

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

/* File name : MammalInt.java */

public class MammalInt implements Animal {

public void eat() {

System.out.println("Mammal eats");

public void travel() {

System.out.println("Mammal travels");

public int noOfLegs() {

return 0;

Page 33 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21

public static void main(String args[]) {

MammalInt m = new MammalInt();

m.eat();

m.travel();

}}

This will produce the following result:


Output
Mammal eats
Mammal travels
When overriding methods defined in interfaces, there are several rules to be followed:
 Checked exceptions should not be declared on implementation methods other than the
ones declared by the interface method or subclasses of those declared by the interface
method.
 The signature of the interface method and the same return type or subtype should be
maintained when overriding the methods.
 An implementation class itself can be abstract and if so, interface methods need not be
implemented.
 When implementation interfaces, there are several rules −
 A class can implement more than one interface at a time.
 A class can extend only one class, but implement many interfaces.
 An interface can extend another interface, in a similar way as a class can extend another
class.
Extending Multiple Interfaces
A Java class can only extend one parent class. Multiple inheritances is not allowed.
Interfaces are not classes, however, and an interface can extend more than one parent
interface.
The extends keyword is used once, and the parent interfaces are declared in a comma-
separated list.
For example, if the Hockey interface extended both Sports and Event, it would be declared as:
Example

public interface Hockey extends Sports, Event

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

public interface EventListener

{}

An interface with no methods in it is referred to as a tagging interface. There are two basic
design purposes of tagging interfaces −

Creates a common parent:


As with the EventListener interface, which is extended by dozens of other interfaces in
the Java API, you can use a tagging interface to create a common parent among a group of
interfaces. For example, when an interface extends EventListener, the JVM knows that this
particular interface is going to be used in an event delegation scenario.

Adds a data type to a class:


This situation is where the term, tagging comes from. A class that implements a tagging
interface does not need to define any methods (since the interface does not have any), but the
class becomes an interface type through polymorphism.

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.

What is Exception in Java


Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.

What is Exception Handling


Exception Handling is a mechanism to handle runtime errors such as Class Not Found
Exception, IO Exception, SQL Exception, Remote Exception, etc.

Advantage of Exception Handling


The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application that is why we
use exception handling.

Let's take a scenario:


1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there are 10 statements in your program and there occurs an exception at
statement 5, the rest of the code will not be executed i.e. statement 6 to 10 will not be

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.

Hierarchy of Java Exception classes


The java.lang.Throwable class is the root class of Java Exception hierarchy which is
inherited by two subclasses: Exception and Error. A hierarchy of Java Exception classes are
given below:

Types of Java Exceptions


There are mainly two types of exceptions: checked and unchecked. Here, an error is considered
as the unchecked exception.

According to Oracle, there are three types of exceptions:


1. Checked Exception
2. Unchecked Exception
3. Error

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.

Java Exception Keywords


There are 5 keywords which are used in handling exceptions in Java.

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.

throw The "throw" keyword is used to throw an exception.

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.

Nested try Statements


The try statement can be nested. That is, a try statement can be inside the block of
another try. Each time a try statement is entered, the context of that exception is pushed on
the stack. If an inner try statement does not have a catch handler for a particular exception, the
stack is unwound and the next try statement’s catch handlers are inspected for a match. This
continues until one of the catch statements succeeds, or until all of the nested try statements
are exhausted. If no catch statement matches, then the Java run-time system will handle the
exception. Here is an example that uses nested try statements:
// An example of nested try statements. class NestTry {
public static void main(String args[]) { try {
int a = args.length;
int b = 42 / a; System.out.println("a = " + a);
try { // nested try block
division by zero
/* If two command-line args are used,
then generate an out-of-bounds exception. */ if(a==2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception

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);
}

} catch(ArithmeticException e) { System.out.println("Divide by 0: " + e);


}
}
}

Java throws keyword

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.

Syntax of java throws


1. return_type method_name() throws exception_class_name{
2. //method code
3. }

Which exception should be declared


Ans) Checked exception only, because:

 Un checked Exception: under your control so correct your code.


 Error: beyond your control e.g. you are unable to do anything if there occurs Virtual
Machine Error or Stack Over flow Error.

Advantage of Java throws keyword


Now Checked Exception can be propagated (forwarded in call stack). It provides
information to the caller of the method about the exception.

Java throws example


Let's see the example of java throws clause which describes that checked exceptions can
be propagated by throws keyword.
1. import java.io.IOException;
2. class Testthrows1{
3. void m()throws IOException{
4. throw new IOException("device error");//checked exception
5. }
6. void n()throws IOException{
7. m();
8. }
9. void p(){
10. try{

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

Output: exception handled

normal flow...

Java throw exception


Java throw keyword
The Java throw keyword is used to explicitly throw an exception. We can throw either checked
or uncheked exception in java by throw keyword. The throw keyword is mainly used to throw
custom exception.

The syntax of java throw keyword is given below:


1. throw exception;
Let's see the example of throw IOException.
1. throw new IOException("sorry device error);

Java throw keyword example


In this example, we have created the validate method that takes integer value as a
parameter. If the age is less than 18, we are throwing the Arithmetic Exception otherwise print
a message welcome to vote.
1. public class TestThrow1{
2. static void validate(int age){
3. if(age<18)
4. throw new ArithmeticException("not valid");
5. else
6. System.out.println("welcome to vote");
7. }
8. public static void main(String args[]){
9. validate(13);
10. System.out.println("rest of the code...");
11. }
12. }
Java finally block
 Java finally block is a block that is used to execute important code such as closing
connection, stream etc.
 Java finally block is always executed whether exception is handled or not.
 Java finally block follows try or catch block.

Page 39 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21

Why use java finally


Finally block in java can be used to put "cleanup" code such as closing a file, closing
connection etc.

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.

Java Multithreading is mostly used in games, animation, etc.


Advantages of Java Multithreading
 It doesn't block the user because threads are independent and you can perform
multiple operations at the same time.
 You can perform many operations together, so it saves time.
 Threads are independent, so it doesn't affect other threads if an exception occurs in a
single thread.

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.

The Main Thread


When a Java program starts up, one thread begins running immediately. This is usually
called the main thread of your program, because it is the one that is executed when your
program begins.

The main thread is important for two reasons:


 It is the thread from which other “child” threads will be spawned.
 Often it must be the last thread to finish execution because it performs various
shutdown actions.

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.

Its general form is shown here:


static Thread currentThread( )
This method returns a reference to the thread in which it is called. Once you have a
reference to the main thread, you can control it just like any other thread.

How to create thread


There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.

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.

Commonly used Constructors of Thread class:


 Thread()
 Thread(String name)
 Thread(Runnable r)
 Thread(Runnable r,String name)

Page 41 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21

Commonly used methods of Thread class:


public void run(): is used to perform action for a thread.
public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
public void join(): waits for a thread to die.
public void join(long miliseconds): waits for a thread to die for the specified milliseconds
public int getPriority(): returns the priority of the thread.
public int setPriority(int priority): changes the priority of the thread.
public String getName(): returns the name of the thread.
public void setName(String name): changes the name of the thread.
public Thread currentThread(): returns the reference of currently executing thread.
public int getId(): returns the id of the thread.
public Thread.State getState(): returns the state of the thread.
public boolean isAlive(): tests if the thread is alive.
public void yield(): causes the currently executing thread object to temporarily pause and allow
other threads to execute.
public void suspend(): is used to suspend the thread(depricated).
public void resume(): is used to resume the suspended thread(depricated).
public void stop(): is used to stop the thread(depricated).
public boolean isDaemon(): tests if the thread is a daemon thread.
public void setDaemon(boolean b): marks the thread as daemon or user thread.
public void interrupt(): interrupts the thread.
public boolean isInterrupted(): tests if the thread has been interrupted.
public static boolean interrupted(): tests if the current thread has been interrupted.

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:

 A new thread starts(with new callstack).


 The thread moves from New state to the Runnable state.
 When the thread gets a chance to execute, its target run() method will run.

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.

Execution of an applet does not begin at main( ). Instead, execution of an applet is


started and controlled with an entirely different mechanism. Once an applet has been
compiled, it is included in an HTML file using the APPLET tag. The applet will be executed by a
Java-enabled web browser when it encounters the APPLET tag within the HTML file.

The applet tag in the html file


<applet code="MyApplet" width=200 height=60>
</applet>

The Applet Class


Applet provides all necessary support for applet execution, such as starting and
stopping. It also provides methods that load and display images, and methods that load and
play audio clips.

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( ).

Simple Applet Display Methods


void drawString(String message, int x, int y) message is the string to be output beginning
at x,y. In a Java window, the upperleft corner is location 0,0.
void setBackground(Color newColor)
void setForeground(Color newColor)
To set the background and the forground color.
Color.black Color.magenta
To obtain the current settings for the background and foreground colors
Color getBackground( ) Color getForeground( )

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

Passing parameters to applet


The PARAM tag allows you to specify applet-specific arguments in an HTML page.
Applets access their attributes with the getParameter( ) method.
< PARAM NAME = AttributeName VALUE = AttributeValue>
< PARAM NAME = AttributeName2 VALUE = AttributeValue>
...
import java.awt.*;
import java.applet.*;
/*
<applet code="ParamDemo" width=300 height=80>
<param name=fontName value=Courier>
<param name=fontSize value=14>
</applet>
*/
public class ParamDemo extends Applet
{ String fontName;
int fontSize;
public void start()
{ String param;
fontName = getParameter("fontName");
if(fontName == null)
fontName = "Not Found";
param = getParameter("fontSize");
try {
if(param != null)
fontSize = Integer.parseInt(param);
else
fontSize = 0;
} catch(NumberFormatException e) {
fontSize = -1;}
Font f=new Font(fontName,Font.BOLD,fontsize);
this.setFont(f);}
public void paint(Graphics g)
{ g.drawString("Font name: " + fontName, 0, 10);

Page 46 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21

g.drawString("Font size: " + fontSize, 0, 26);


}}
The HTML APPLET Tag
The APPLET tag is used to start an applet from both an HTML document and from an
applet viewer.
The syntax for the standard APPLET tag is :-
< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]
>
[< PARAM NAME = AttributeName VALUE = AttributeValue>]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue>]
...
</APPLET>
CODEBASE :
CODEBASE specifies the directory that will be searched for the applet's executable class
file (specified by the CODE tag). The HTML document's URL directory is used as the CODEBASE if
this attribute is not specified.

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.

WIDTH and HEIGHT:


WIDTH and HEIGHT are required attributes that give the size (in pixels) of the applet
display area.

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

VSPACE and HSPACE:


These attributes are optional. VSPACE specifies the space, in pixels, above and below
the applet. HSPACE specifies the space, in pixels, on each side of the applet.

PARAM NAME and VALUE:


The PARAM tag allows you to specify applet-specific arguments in an HTML page.
Applets access their attributes with the get Parameter( ) method.

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

Working with Graphics


The AWT supports a rich set of graphics methods. All graphics are drawn relative to a window.
The origin of each window is at the top-left corner and is 0,0. Coordinates are specified in
pixels. All output to a window takes place through a graphics context.

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.

Drawing Ellipses and Circles


To draw an ellipse, use drawOval( ). To fill an ellipse, use fillOval(
void drawOval(int top, int left, int width, int height)
void fillOval(int top, int left, int width, int height)
The ellipse is drawn within a bounding rectangle whose upper-left corner is specified by top,left
and whose width and height are specified by width and height. To draw a circle,specify a square
as the bounding rectangle.

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.

Working with colors


Java supports color in a portable, device-independent fashion. The AWT color system allows
you to specify any color you want. It then finds the best match for that color, given the limits of
the display hardware currently executing your program or applet. Color is encapsulated by the
Color class.

Three commonly used forms are shown here:


Color(int red, int green, int blue)
Color(int rgbValue)
Color(float red, float green, float blue)
The first constructor takes three integers that specify the color as a mix of red, green,
and blue. These values must be between 0 and 255, as in this example: new Color(255, 100,
100); // light red
The second color constructor takes a single integer that contains the mix of red, green,
and blue packed into an integer. The integer is organized with red in bits 16 to 23, green in bits
8 to 15, and blue in bits 0 to 7. Here is an example of this constructor:
int newRed = (0xff000000 | (0xc0 << 16) | (0x00 << 8) | 0x00);
Color darkRed = new Color(newRed);
The final constructor, Color(float, float, float), takes three float values (between 0.0 and 1.0)
that specify the relative mix of red, green, and blue.

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

Working with Fonts


The AWT supports multiple type fonts. Years ago, fonts emerged from the domain of
traditional typesetting to become an important part of computer-generated documents and
displays. The AWT provides flexibility by abstracting font-manipulation operations and allowing
for dynamic selection of fonts.

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.

The Font class defines these protected variables:


Variable : Meaning
String name : Name of the font
float pointSize : Size of the font in points
int size : Size of the font in points
int style : Font style

Several static fields are also defined.


Method : Description
static Font decode(String str) : Returns a font given its name.
boolean equals(Object FontObj) : Returns true if the invoking object contains the
same font as that specified by FontObj. Otherwise, it
returns false.
String get Family( ) : Returns the name of the font family to which the
invoking font belongs.
static Font getFont(String property) : Returns the font associated with the system property
Specified by property. null is returned if property does not
exist.
Static Font get Font : Returns the font associated with the system property
specified by property. The font specified by default Font
is returned if property does not exist.
String getFontName() : Returns the face name of the invoking font.
String getName( ) : Returns the logical name of the invoking font.
int getSize( ) : Returns the size, in points, of the invoking font.
int getStyle( ) : Returns the style values of the invoking font.
int hashCode( ) : Returns the hash code associated with the invoking
object.
boolean is Bold( ) : Returns true if the font includes the BOLD style value.
Otherwise, false is returned.
boolean is Italic( ) : Returns true if the font includes the ITALIC style value.
Otherwise, false is returned.

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.

The general form of method to register a listener is:


Public void addTypeListener(TypeListener eventListener)

Page 53 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21

The general form of method to unregister a listener is:


Public void removeTypeListener(TypeListener eventListener)

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

The general form of the adjustment Value Changed() method is


Void adjustment Value Changed (Adjustment Event e) Where e is the reference to an
object of Adjustment Event class.

Item Listener Interface


The method item State Changed() defined by the itemlistener interface is invoked when
the state of an item is changed. The object of ItemEvent class is passed as method parameter.

The syntax of the method is


Void item State Changed (Item Event item)

Key Listener interface


The methods defined in Key Listener interface are invoked when any key is pressed or
released or a character is entered.

The methods are


Void keyPressed(KeyEvent e)
Void keyReleased(KeyEvent e)

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.

The Mouse Listener Interface and Mouse Motion Listener Interface


The method s defined by the Mouse Listener interface are invoked when the mouse is
clicked, pressed, released and when the mouse enters or exits the component. The methods
defined by the Mouse Motion Listener interface are invoked when the mouse is dragged or
moved from one position to another. The object Mouse Event is passed as method parameter.

The methods are


void mousePressed(MouseEvent e)
void mouseReleased(MouseEvent e)
void mouseClicked(MouseEvent e)
void mouseEntered(MouseEvent e)
Void mouseExited(MouseEvent e)

The methods defined in MouseMotionListener interface is


Void mouseMoved(MouseEvent e)
Void mouseDragged(MouseEvent me)

The TextListener interface


The method textValueChanged() defined by the TextListener interface is invoked when the text
inside the text area or textfield alters.
The syntax of the method is
Void textValueChanged(TextEvent e)
The WindowListenerInterface
The method s defined by the WindowListener inteface are invoked when the state of the
window changes.The methods are
public void windowOpened(WindowEvent e)
Invoked the first time the window is made visible.
public void windowClosed(WindowEvent e)
Invoked when a window has been closed
public void windowClosing(WindowEvent e)
Invoked when the user attempts to close the window

Page 55 of 61
STUDY MATERIAL FOR B.SC CS
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020-21

public void windowActivated(WindowEvent e)


Invoked when the Window is set to be the active Window.
public void windowDeactivated(WindowEvent e)
Invoked when a Window is no longer the active Window.
public void windowIconified(WindowEvent e)
Invoked when a window is changed from a normal to a minimized state.
public void windowDeiconified(WindowEvent e)
Invoked when a window is changed from a minimized to a normal state.
/*<applet code=ButTextLabel width=300 height=400>
</applet>*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class ButTextLabel extends Applet implements ActionListener
{
TextField t1; TextField t2; TextField t3;
Button bAdd;
Button bsub;
Label l1;
Label l2;
public void init()
{
bAdd=new Button("add");
bsub=new Button("Sub");
t1=new TextField(10);
t2=new TextField(15);
t3=new TextField(15);
l1=new Label("Enter First Number");
l2=new Label("Enter Second Number");
this.add(l1); this.add(t1); this.add(l2); this.add(t2); this.add(bAdd);
this.add(bsub);
this.add(t3);
bAdd.addActionListener(this);

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

Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based


applications in java. Java AWT components are platform-dependent i.e. components are
displayed according to the view of operating system. AWT is heavyweight i.e. its components
are using the resources of OS. The java.awt package provides classes for AWT api such
as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc.

Java AWT Hierarchy


The hierarchy of Java AWT classes are given below:

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

Useful Methods of Component class

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

Java AWT Menu Item and Menu:


The object of MenuItem class adds a simple labeled menu item on menu. The items
used in a menu must belong to the MenuItem or any of its subclass. The object of Menu class is
a pull down menu component which is displayed on the menu bar. It inherits the Menu Item
class.

AWT Menu Item class declaration:


public class MenuItem extends MenuComponent implements Accessible
AWT Menu class declaration
public class Menu extends MenuItem implements MenuContainer, Accessible
Java AWT MenuItem and Menu Example

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

You might also like