S4 Java Full

Download as pdf or txt
Download as pdf or txt
You are on page 1of 63

Programming in Java

CS 1444 Programming in Java


S4 B.Sc Computer Science

Name : ……………………………………………………………………………………………

Candidate Code: ……………………………………………………………………………..

Muslim Association College of Arts and Science Page 1


Programming in Java

MODULE 1

Muslim Association College of Arts and Science Page 2


Programming in Java

History of Java
• Java Programming Language was written by James Gosling along with two other person ‘Mike
Sheridan‘ and ‘Patrick Naughton‘, while they were working at Sun Microsystems.
• It was Initially it was named oak .
• The latest Releases is : Java Version 1.8 is the current stable release which was released this
year (2015).
• Java is implemented over a number of places in modern world. It is implemented as Standalone
Application, Web Application, Enterprise Application and Mobile Application. Games, Smart
Card, Embedded System, Robotics, Desktop, etc.

Five Goals which were taken into consideration while developing Java:

1. Keep it simple, familiar and object oriented.


2. Keep it Robust and Secure.
3. Keep it architecture-neural and portable.
4. Executable with High Performance.
5. Interpreted, threaded and dynamic

Special Features of Java


1.General Purpose

Java capabilities are not limited to any specific application domain rather it can be used in various
application domain and hence it is called General Purpose Programming Language.

2.Class based

Java is a class based/oriented programming language which means Java supports inheritance feature of
object-oriented Programming Language.

3.Object oriented

Java is object-oriented means software developed in Java are combination of different types of object.

4.Platform Independent

A Java code will run on any JVM (Java Virtual Machine). Literally you can run same Java code on
Windows JVM, Linux JVM, Mac JVM or any other JVM practically and get same result every time

Muslim Association College of Arts and Science Page 3


Programming in Java

5.Architecturally Neutral

A Java code is not dependent upon Processor Architecture. A Java Application compiled on 64 bit
architecture of any platform will run on 32 bit (or any other architecture) system without any issue.

6.Multithreaded

A thread in Java refers to an independent program. Java supports multithread which means Java is
capable of running many tasks simultaneously, sharing the same memory.

7.Dynamic

Java is a Dynamic programming language which means it executes many programming behavior at
Runtime and don’t need to be passed at compile time as in the case of static programming.

8.Distributed

Java Supports distributed System which means we can access files over Internet just by calling the
methods.

9.Portable

A Java program when compiled produce bytecodes. Bytecodes are magic. These bytecodes can be
transferred via network and can be executed by any JVM, hence came the concept of ‘Write once, Run
Anywhere(WORA)’.

10.Robust

Java is a robust programming Language which means it can cope with error while the program is
executing as well as keep operating with abnormalities to certain extent. Automatic Garbage collection,
strong memory management, exception handling and type checking further adds to the list.

11.Interpreted

Java is a compiled programming Language which compiles the Java program into Java byte codes. This
JVM is then interpreted to run the program.

12.Security

Unlike other programming Language where Program interacts with OS using User runtime environment
of OS, Java provides an extra layer of security by putting JVM between Program and OS.

13.Simple Syntax

Java is an improved c++ which ensures friendly syntax but with removed unwanted features and
inclusion of Automatic Garbage collection.

Muslim Association College of Arts and Science Page 4


Programming in Java

14.High Level Programming Language

Java is a High Level Programming Language the syntax of which is human readable. Java lets
programmer to concentrate on what to achieve and not how to achieve. The JVM converts a Java
Program to Machine understandable language.

15.High Performance

Java make use of Just-In-Time compiler for high performance. Just-In-Time compiler is a computer
program that turns Java byte codes into instructions that can directly be sent to compilers.

Data Types in Java


Data types specify the different sizes and values that can be stored in the variable. There are two types
of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float
and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

DataType

Primitive Non primitive

Boolean Numbers Characters

Integers Floating

1.Byte 1.Float 1.Char 1.Class


2.Short 2.Double 2.String 2.Interfaces
3.Int 3.Array
4.Long

1.Java Primitive Data Types

• In Java language, primitive data types are the building blocks of data manipulation. These are

the most basic data types available in Java language.


• A primitive data type specifies the size and type of variable values, and it has no additional
methods.

Muslim Association College of Arts and Science Page 5


Programming in Java

1.1 Booleans

A boolean data type is declared with the boolean keyword and can only take the values true or false:

Example :

boolean a= true;
boolean b= false;
System.out.println(a); // Outputs true
System.out.println(b); // Outputs false

Boolean values are mostly used for conditional testing, which you will learn more about in a later
chapter.

1.2 Numbers

Primitive number types are divided into two groups:

• Integer types stores whole numbers, positive or negative (such as 123 or -456), without
decimals. Valid types are byte, short, int and long. Which type you should use, depends on the
numeric value.
• Floating point types represents numbers with a fractional part, containing one or more
decimals. There are two types: float and double.

( I )Integer Types

1.Byte
The byte data type can store whole numbers from -128 to 127. This can be used instead of int or other
integer types to save memory when you are certain that the value will be within -128 and 127:
Example: byte a = 100;
2.Short
The short data type can store whole numbers from -32768 to 32767:
Example : short a = 5000;

3.Int
The int data type can store whole numbers from -2147483648 to 2147483647.In general, and in our
tutorial, the int data type is the preferred data type when we create variables with a numeric value.
int a= 100000;

4.Long

The long data type can store whole numbers from -9223372036854775808 to 9223372036854775807.
This is used when int is not large enough to store the value. Note that you should end the value with an
"L":

Muslim Association College of Arts and Science Page 6


Programming in Java

Example : long a = 15000000000L;

( II )Floating Point Types

You should use a floating point type whenever you need a number with a decimal, such as 9.99 or
3.14515.

1.Float

The float data type can store fractional numbers from 3.4e−038 to 3.4e+038. Note that you should end
the value with an "f":
Eg:float a= 5.75f;

2.Double

The double data type can store fractional numbers from 1.7e−308 to 1.7e+038. Note that you should
end the value with a "d":
Eg:double a= 19.99d;

1.3 Characters

1.char

The char data type is used to store a single character. The character must be surrounded by single
quotes, like 'A' or 'c':

char a = 'B';

2.Strings

The String data type is used to store a sequence of characters (text). String values must be surrounded
by double quotes:

Example
String greeting = "Hello World";

2.Non-Primitive Data Types

Non-primitive data types are called reference types because they refer to objects.

The main difference between primitive and non-primitive data types are:

Muslim Association College of Arts and Science Page 7


Programming in Java

• Primitive types are predefined (already defined) in Java. Non-primitive types are created by the
programmer and is not defined by Java (except for String).
• Non-primitive types can be used to call methods to perform certain operations, while primitive
types cannot.
• A primitive type has always a value, while non-primitve types can be null.
• A primitive type starts with a lowercase letter, while non-primitive types starts with an
uppercase letter.
• The size of a primitive type depends on the data type, while non-primitive types have all the
same size.

Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc. You will learn more about
these in a later chapter.

Java Type Casting


Type casting is when you assign a value of one primitive data type to another type.

In Java, there are two types of casting:

1. Widening Casting (automatically) - converting a smaller type to a larger type size


byte -> short -> char -> int -> long -> float -> double

2. Narrowing Casting (manually) - converting a larger type to a smaller size type


double -> float -> long -> int -> char -> short -> byte

1.Widening Casting

Widening casting is done automatically when passing a smaller size type to a larger size type:
int a = 9;
double b = a; // Automatic casting: int to double
System.out.println(a); // Outputs 9
System.out.println(b); // Outputs 9.0

2.Narrowing Casting

Narrowing casting must be done manually by placing the type in parantheses in front of the value:

double a = 9.78;
int b= (int) a; // Manual casting: double to int

System.out.println(myDouble); // Outputs 9.78


System.out.println(myInt); // Outputs 9

Muslim Association College of Arts and Science Page 8


Programming in Java

Java Operators
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into
the following groups −

1. Arithmetic Operators
2. Relational Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Misc Operators

1.The Arithmetic Operators


Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists the arithmetic operators −

Assume integer variable A holds 10 and variable B holds 20, then −

Operator Description Example

Adds values on either side of the operator. A+B


+ (Addition) will give
30

Subtracts right-hand operand from left-hand operand. A - B will


- (Subtraction)
give -10

Multiplies values on either side of the operator. A*B


* (Multiplication) will give
200

Divides left-hand operand by right-hand operand. B/A


/ (Division) will give
2

Muslim Association College of Arts and Science Page 9


Programming in Java

Divides left-hand operand by right-hand operand and returns B%A


% (Modulus) remainder. will give
0

Increases the value of operand by 1. B++


++ (Increment)
gives 21

Decreases the value of operand by 1. B-- gives


-- (Decrement)
19

2.The Relational Operators


There are following relational operators supported by Java language.

Assume variable A holds 10 and variable B holds 20, then −

Show Examples

Operator Description Example

Checks if the values of two operands are equal or not, if yes (A == B) is not
== (equal to)
then condition becomes true. true.

Checks if the values of two operands are equal or not, if


!= (not equal to) (A != B) is true.
values are not equal then condition becomes true.

Checks if the value of left operand is greater than the value


> (greater than) (A > B) is not true.
of right operand, if yes then condition becomes true.

Checks if the value of left operand is less than the value of


< (less than) (A < B) is true.
right operand, if yes then condition becomes true.

Checks if the value of left operand is greater than or equal


>= (greater than (A >= B) is not
to the value of right operand, if yes then condition

Muslim Association College of Arts and Science Page 10


Programming in Java

or equal to) becomes true. true.

Checks if the value of left operand is less than or equal to


<= (less than or
the value of right operand, if yes then condition becomes (A <= B) is true.
equal to)
true.

3.The Bitwise Operators


Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char,
and byte.

Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in
binary format they will be as follows −

a = 0011 1100

b = 0000 1101

-----------------

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a = 1100 0011

4.The Logical Operators


The following table lists the logical operators −

Assume Boolean variables A holds true and variable B holds false, then −

Show Examples

Operator Description Example

Called Logical AND operator. If both the


&& (logical and) operands are non-zero, then the (A && B) is false
condition becomes true.

Muslim Association College of Arts and Science Page 11


Programming in Java

Called Logical OR Operator. If any of the


|| (logical or) two operands are non-zero, then the (A || B) is true
condition becomes true.

Called Logical NOT Operator. Use to


reverses the logical state of its operand. If
! (logical not) !(A && B) is true
a condition is true then Logical NOT
operator will make false.

5.The Assignment Operators


Following are the assignment operators supported by Java language −

Show Examples

Operator Description Example

Simple assignment operator. Assigns values from right side C = A + B will


= operands to left side operand. assign value
of A + B into C

Add AND assignment operator. It adds right operand to the left C += A is


+= operand and assign the result to left operand. equivalent to
C=C+A

Subtract AND assignment operator. It subtracts right operand from C -= A is


-= the left operand and assign the result to left operand. equivalent to
C=C–A

Multiply AND assignment operator. It multiplies right operand with C *= A is


*= the left operand and assign the result to left operand. equivalent to
C=C*A

/= Divide AND assignment operator. It divides left operand with the C /= A is


equivalent to

Muslim Association College of Arts and Science Page 12


Programming in Java

right operand and assign the result to left operand. C=C/A

Modulus AND assignment operator. It takes modulus using two C %= A is


%= operands and assign the result to left operand. equivalent to
C=C%A

6.Miscellaneous Operators
There are few other operators supported by Java Language.

6.1 Conditional Operator ( ? : )


Conditional operator is also known as the ternary operator. This operator consists of three operands
and is used to evaluate Boolean expressions. The goal of the operator is to decide, which value should
be assigned to the variable.

6.2 instanceof Operator


This operator is used only for object reference variables. The operator checks whether the object is of a
particular type (class type or interface type). instanceof operator is written as −

( Object reference variable ) instanceof (class/interface type)

If the object referred by the variable on the left side of the operator passes the IS-A check for the
class/interface type on the right side, then the result will be true. Following is an example −

Java Syntax
In the previous chapter, we created a Java file called MyClass.java, and we used the following code to
print "Hello World" to the screen:

MyClass.java

public class MyClass

{
public static void main(String[] args)

{
System.out.println("Hello World");
}
}

Muslim Association College of Arts and Science Page 13


Programming in Java

Control Structures
I .Conditional Statements
1.1 The if Statement

Use the if statement to specify a block of Java code to be executed if a condition is true.
Syntax:
if (condition)
{
// block of code to be executed if the condition is true
}

Example:
if (20 > 18)
{
System.out.println("20 is greater than 18");
}
1.2 If else Statement

Use the else statement to specify a block of code to be executed if the condition is false inside the if
block.
Syntax:
if (condition)
{
// block of code to be executed if the condition is true
}
else
{
// block of code to be executed if the condition is false
}
Example :
int time = 20;
if (time < 18)
{
System.out.println("Good day.");
}

else

{
System.out.println("Good evening.");
}

Muslim Association College of Arts and Science Page 14


Programming in Java

1.3 The else if Statement

Use the else if statement to specify a new condition if the first condition is false.

Syntax
if (condition1)
{
// block of code to be executed if condition1 is true
} else if (condition2)
{
// block of code to be executed if the condition1 is false and condition2 is true
}
else
{
// block of code to be executed if the condition1 is false and condition2 is false
}

Example :
int time = 22;
if (time < 10)
{
System.out.println("Good morning.");
} else if (time < 20)
{
System.out.println("Good day.");
}
Else
{
System.out.println("Good evening.");
}
// Outputs "Good evening."
1.4 Switch Statements

Use the switch statement to select one of many code blocks to be executed.

switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

Muslim Association College of Arts and Science Page 15


Programming in Java

This is how it works:

• The switch expression is evaluated once.


• The value of the expression is compared with the values of each case.
• If there is a match, the associated block of code is executed.
• The break and default keywords are optional, and will be described later in this chapter

The example below uses the weekday number to calculate the weekday name:

int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
}
// Outputs "Thursday" (day 4)

Java Loops
Loops can execute a block of code as long as a specified condition is reached.

1.Java While Loop

The while loop loops through a block of code as long as a specified condition is true:

Muslim Association College of Arts and Science Page 16


Programming in Java

Syntax
while (condition)

{
// code block to be executed
}
In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less
than 5:

Example
int i = 0;
while (i < 5)

{
System.out.println(i);
i++;
}

2.The Do/While Loop

The do/while loop is a variant of the while loop. This loop will execute the code block once, before
checking if the condition is true, then it will repeat the loop as long as the condition is true.

Syntax
do

{
// code block to be executed
}
while (condition);

Example
int i = 0;
do

{
System.out.println(i);
i++;
}
while (i < 5);

Muslim Association College of Arts and Science Page 17


Programming in Java

3.Java For Loop

When you know exactly how many times you want to loop through a block of code, use the for loop
instead of a while loop:

Syntax
for (statement 1; statement 2; statement 3)

{
// code block to be executed
}

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

Example
for (int i = 0; i < 5; i++)

{
System.out.println(i);
}

Example explained
Statement 1 sets a variable before the loop starts (int i = 0).
Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is true, the loop will
start over again, if it is false, the loop will end.
Statement 3 increases a value (i++) each time the code block in the loop has been executed.

4.For-Each Loop

There is also a "for-each" loop, which is used exclusively to loop through elements in an array:

for (type variable : arrayname)

{
// code block to be executed
}

Muslim Association College of Arts and Science Page 18


Programming in Java

The following example outputs all elements in the cars array, using a "for-each" loop:

Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars)

{
System.out.println(i);
}

Java Break and Continue


Java Break

You have already seen the break statement used in an earlier chapter of this tutorial. It was used to
"jump out" of a switch statement.

The break statement can also be used to jump out of a loop.

This example jumps out of the loop when i is equal to 4:

Example
for (int i = 0; i < 10; i++)
{
if (i == 4)
{
break;
}
System.out.println(i);
}
Java Continue

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues
with the next iteration in the loop.

This example skips the value of 4:

Example
for (int i = 0; i < 10; i++)
{
if (i == 4) {
continue;
}
System.out.println(i);
}

Muslim Association College of Arts and Science Page 19


Programming in Java

Java Arrays
• Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.
• To declare an array, define the variable type with square brackets:
• String[] cars;

• We have now declared a variable that holds an array of strings. To insert values to it, we can use
an array literal - place the values in a comma-separated list, inside curly braces:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

To create an array of integers, you could write:

int[] myNum = {10, 20, 30, 40};

Access the Elements of an Array

• You access an array element by referring to the index number.


• This statement accesses the value of the first element in cars:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


System.out.println(cars[0]);

Array Length

To find out how many elements an array has, use the length property:

Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
// Outputs 4

Loop Through an Array

You can loop through the array elements with the for loop, and use the lengthproperty to specify how
many times the loop should run.

The following example outputs all elements in the cars array:

Muslim Association College of Arts and Science Page 20


Programming in Java

Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++)

{
System.out.println(cars[i]);
}

Multidimensional Arrays

• A multidimensional array is an array containing one or more arrays.


• To create a two-dimensional array, add each array within its own set of curly braces:

Example
int[][] a= { {1, 2, 3, 4}, {5, 6, 7} };

myNumbers is now an array with two arrays as its elements.

To access the elements of the a array, specify two indexes: one for the array, and one for the element
inside that array. This example accesses the third element (2) in the second array (1) of a:

Example
int[][] a = { {1, 2, 3, 4}, {5, 6, 7} };
int x = a[1][2];
System.out.println(x); // Outputs 7

Constructor
Constructor in java is a special type of method that is used to initialize the object.Java constructor is
invoked at the time of object creation. It constructs the values i.e. provides data for the object that is
why it is known as constructor.

Rules for creating java constructor

There are basically two rules defined for the constructor.

• Constructor name must be same as its class name


• Constructor must have no explicit return type

Types of java constructors : There are two types of constructors:

1. Default constructor (no-argu constructor)


2. Parameterized constructor

Muslim Association College of Arts and Science Page 21


Programming in Java

1. Java Default Constructor


A constructor that have no parameter is known as default constructor.

Syntax of default constructor:

class_name()

Example of default constructor

In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of
object creation.

class Bike1
{
Bike1()
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1();
}
}

Output:
Bike is created

Q) What is the purpose of default constructor?

Default constructor provides the default values to the object like 0, null etc. depending on the type.

Example of default constructor that displays the default values

Muslim Association College of Arts and Science Page 22


Programming in Java

class Student3
{
int id;
String name;
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}
Output:
0 null
0 null

Explanation:In the above class,you are not creating any constructor so compiler provides you a default
constructor.Here 0 and null values are provided by default constructor.

2.Java parameterized constructor


• A constructor that have parameters is known as parameterized constructor.
• Parameterized constructor is used to provide different values to the distinct objects.
• In this example, we have created the constructor of Student class that have two parameters. We
can have any number of parameters in the constructor.

class Student4
{
int id;
String name;
Student4(int i,String n)
{
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}

Muslim Association College of Arts and Science Page 23


Programming in Java

public static void main(String args[])


{
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan
Constructor Overloading in Java
Constructor overloading is a technique in Java in which a class can have any number of constructors that
differ in parameter lists.The compiler differentiates these constructors by taking into account the
number of parameters in the list and their type.

Example of Constructor Overloading

class Student5
{
int id;
String name;
int age;
Student5(int i,String n)
{
id = i;
name = n;
}
Student5(int i,String n,int a)
{
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}
public static void main(String args[])
{
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}

Muslim Association College of Arts and Science Page 24


Programming in Java

Output:
111 Karan 0
222 Aryan 25

Java Copy Constructor


• There is no copy constructor in java. But, we can copy the values of one object to another like
copy constructor in C++.
• There are many ways to copy the values of one object into another in java.
• They are:
In this example, we are going to copy the values of one object into another using java constructor.

class Student6
{
int id;
String name;
Student6(int i,String n)
{
id = i;
name = n;
}

Student6(Student6 s)
{
id = s.id;
name =s.name;
}
void display()
{
System.out.println(id+" "+name);
}

public static void main(String args[])


{
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}
Output:
111 Karan
111 Karan
Q) Does constructor return any value?
Ans:yes, that is current class instance (You cannot use return type yet it returns a value).

Muslim Association College of Arts and Science Page 25


Programming in Java

Applet in java
An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java
application because it has the entire Java API at its disposal.

There are some important differences between an applet and a standalone Java application, including
the following −

• An applet is a Java class that extends the java.applet.Applet class.


• A main() method is not invoked on an applet, and an applet class will not define main().
• Applets are designed to be embedded within an HTML page.
• When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
• A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or a
separate runtime environment.
• The JVM on the user's machine creates an instance of the applet class and invokes various
methods during the applet's lifetime.
• Applets have strict security rules that are enforced by the Web browser. The security of an
applet is often referred to as sandbox security, comparing the applet to a child playing in a
sandbox with various rules that must be followed.
• Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.

Life Cycle of an Applet


Four methods in the Applet class gives you the framework on which you build any serious applet −

1. init − This method is intended for whatever initialization is needed for your applet. It is called
after the param tags inside the applet tag have been processed.
2. start − This method is automatically called after the browser calls the init method. It is also
called whenever the user returns to the page containing the applet after having gone off to
other pages.
3. stop − This method is automatically called when the user moves off the page on which the
applet sits. It can, therefore, be called repeatedly in the same applet.
4. destroy − This method is only called when the browser shuts down normally. Because applets
are meant to live on an HTML page, you should not normally leave resources behind after a user
leaves the page that contains the applet.
5. paint − Invoked immediately after the start() method, and also any time the applet needs to
repaint itself in the browser. The paint() method is actually inherited from the java.awt.

Muslim Association College of Arts and Science Page 26


Programming in Java

Example:

Import java.applet.*;
import java.awt.*;
public class myapplet extends Applet
{
public void paint (Graphics g) {
g.drawString ("Hello World", 25, 50);
}
}
Invoking an Applet
An applet may be invoked by embedding directives in an HTML file and viewing the file through an
applet viewer or Java-enabled browser.

The <applet> tag is the basis for embedding an applet in an HTML file. Following is an example that
invokes the "Hello, World" applet −

<html>

<applet code = "HelloWorldApplet.class" width = "320" height = "120">

</applet>

</html>

Finalize or Finalizer in Java


The java.lang.Object.finalize() is called by the garbage collector on an object when garbage collection
determines that there are no more references to the object. A subclass overrides the finalize method to
dispose of system resources or to perform other cleanup.

Declaration

Following is the declaration for java.lang.Object.finalize() method

protected void finalize()

• There is no parameters in Finalizer method.


• This method does not have any return a value.
• Exception raised by this method is throwable

Muslim Association College of Arts and Science Page 27


Programming in Java

Nested Classes
In Java, just like methods, variables of a class too can have another class as its member. Writing a class
within another is allowed in Java. The class written within is called the nested class, and the class that
holds the inner class is called the outer class.

Following is the syntax to write a nested class. Here, the class Outer_Demo is the outer class and the
class Inner_Demo is the nested class.

class Outer_Demo
{
class Nested_Demo
{
}
}
Inner Classes
• Inner Classes (Non-static Nested Classes)
• Inner classes are a security mechanism in Java.
• We know a class cannot be associated with the access modifier private, but if we have the class
as a member of other class, then the inner class can be made private. And this is also used to
access the private members of a class.
• Inner classes are of three types depending on how and where you define them. They are −
• Creating an inner class is quite simple. You just need to write a class within a class. Unlike a
class, an inner class can be private and once you declare an inner class private, it cannot be
accessed from an object outside the class.
• Following is the program to create an inner class and access it. In the given example, we make
the inner class private and access the class through a method.

Example

class Outer_Demo
{
int num;
// inner class
private class Inner_Demo
{
public void print()
{
System.out.println("This is an inner class");
}
}
// Accessing he inner class from the method within
void display_Inner()

Muslim Association College of Arts and Science Page 28


Programming in Java

{
Inner_Demo inner = new Inner_Demo();
inner.print();
}
}

public class My_class {

public static void main(String args[]) {


// Instantiating the outer class
Outer_Demo outer = new Outer_Demo();

// Accessing the display_Inner() method.


outer.display_Inner();
}
}
Here you can observe that Outer_Demo is the outer class, Inner_Demo is the inner class, display_Inner()
is the method inside which we are instantiating the inner class, and this method is invoked from the
main method.
If you compile and execute the above program, you will get the following result −

Output

This is an inner class.

Muslim Association College of Arts and Science Page 29


Programming in Java

MODULE 2

Muslim Association College of Arts and Science Page 30


Programming in Java

Inheritance
Inheritance can be defined as the process where one class acquires the properties (methods and fields)
of another. With the use of inheritance the information is made manageable in a hierarchical order.

The class which inherits the properties of other is known as subclass (derived class, child class) and the
class whose properties are inherited is known as superclass (base class, parent class).

extends Keyword
extends is the keyword used to inherit the properties of a class. Following is the syntax of extends
keyword

Syntax

class A
{
.....
.....
}
class B extends A
{
.....
.....
}
Following is an example demonstrating Java inheritance. In this example, you can observe two classes
namely Calculation and My_Calculation.
Using extends keyword, the My_Calculation inherits the methods addition() and Subtraction() of
Calculation class.

class Calculation
{
int z;
public void addition(int x, int y)
{
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}
public void Subtraction(int x, int y)
{
z = x - y;
System.out.println("The difference between the given numbers:"+z);
}

Muslim Association College of Arts and Science Page 31


Programming in Java

public class My_Calculation extends Calculation


{
public void multiplication(int x, int y)
{
z = x * y;
System.out.println("The product of the given numbers:"+z);
}

public static void main(String args[])


{
int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
}
Output
The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200

Super Keyword

• The super keyword is similar to this keyword. Following are the scenarios where the super
keyword is used.
• It is used to differentiate the members of superclass from the members of subclass, if they have
same names.
• It is used to invoke the superclass constructor from subclass.

Differentiating the Members

If a class is inheriting the properties of another class. And if the members of the superclass have the
names same as the sub class, to differentiate these variables we use super keyword as shown below.

super.variable

super.method();

Muslim Association College of Arts and Science Page 32


Programming in Java

Types of Inheritance

Interface in Java
• An interface in java is a blueprint of a class. It has static constants and abstract methods.
• The interface in java is a mechanism to achieve abstraction. There can be only abstract methods
in the java interface not method body. It is used to achieve abstraction and multiple inheritance
in Java.
• Java Interface also represents IS-A relationship.
• It cannot be instantiated just like abstract class.

Why use Java interface?

1. It is used to achieve abstraction.


2. By interface, we can support the functionality of multiple inheritance.
3. It can be used to achieve loose coupling.

Syntax

Interface interfacename
{
Interface methods();
}

Muslim Association College of Arts and Science Page 33


Programming in Java

Example
interface printable
{
void print();
}
class A6 implements printable
{
public void print()
{
System.out.println("Hello");
}

public static void main(String args[])


{
A6 obj = new A6();
obj.print();
}
}

Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as
multiple inheritance.

Muslim Association College of Arts and Science Page 34


Programming in Java

interface Printable
{
void print();
}
interface Showable
{
void show();
}
class A7 implements Printable,Showable
{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome")
}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:
Hello
Welcome

Multiple inheritance is not supported through class in java but it is possible by


interface, why?

As we have explained in the inheritance chapter, multiple inheritance is not supported in case of class
because of ambiguity. But it is supported in case of interface because there is no ambiguity as
implementation is provided by the implementation class. For example:

Method- Overriding
• If a class inherits a method from its superclass, then there is a chance to override the method
provided that it is not marked final.
• The benefit of overriding is: ability to define a behavior that's specific to the subclass type, which
means a subclass can implement a parent class method based on its requirement.
• In object-oriented terms, overriding means to override the functionality of an existing method.

Muslim Association College of Arts and Science Page 35


Programming in Java

Example

class Animal
{
public void move()
{
System.out.println("Animals can move");
}
}
class Dog extends Animal
{
public void move() {
System.out.println("Dogs can walk and run");
}
}

public class TestDog


{

public static void main(String args[])


{
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object

a.move(); // runs the method in Animal class


b.move(); // runs the method in Dog class
}
}
This will produce the following result −

Output
Animals can move
Dogs can walk and run

Method Overloading
Method overloading is the way of implementing static/compile time polymorphism in java. Method
overloading means more than one methods in a class with same name but different parameters.
Parameters can be differing in types, numbers or order.

Advantage of method overloading

• Method overloading increases the readability of the program.


• So, we perform method overloading to figure out the program quickly.

Muslim Association College of Arts and Science Page 36


Programming in Java

Different ways to overload the method

1. By changing the no. of arguments


2. By changing the data ty

1) Method Overloading: changing no. of arguments

• In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.
• In this example, we are creating static methods so that we don't need to create instance for
calling methods.

class Adder
{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}
Output:
22

33

2) Method Overloading: changing data type of arguments

In this example, we have created two methods that differs in data type. The first add method receives
two integer arguments and second add method receives two double arguments.

class Adder
{
static int add(int a, int b)
{
return a+b;
}

Muslim Association College of Arts and Science Page 37


Programming in Java

static double add(double a, double b)


{
return a+b;
}
}
class TestOverloading2
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}
}
Output:
22
24.9

Abstraction in Java
• Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
• Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery.
• Abstraction lets you focus on what the object does instead of how it does it.

There are two ways to achieve abstraction in java

1. Abstract class
2. Interface

Abstract class in Java

A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract
methods. It needs to be extended and its method implemented. It cannot be instantiated.

o An abstract class must be declared with an abstract keyword.


o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the method.

Muslim Association College of Arts and Science Page 38


Programming in Java

Example of abstract class

In this example, Bike is an abstract class that contains only one abstract method run. Its implementation
is provided by the Honda class.

abstract class Bike


{
abstract void run();
}
class Honda4 extends Bike
{
void run()
{
System.out.println("Abstrcat method running safely");
}
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
}
}
Test it Now
OUTPUT: Abstrcat method running safely

Interface in Java
• An interface in java is a blueprint of a class. It has static constants and abstract methods.
• The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods
in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance
in Java.
• In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.
• Java Interface also represents the IS-A relationship.
• It cannot be instantiated just like the abstract class.

There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

Muslim Association College of Arts and Science Page 39


Programming in Java

How to declare an interface?

An interface is declared by using the interface keyword. It provides total abstraction; means all the
methods in an interface are declared with the empty body, and all the fields are public, static and final
by default. A class that implements an interface must implement all the methods declared in the
interface.

Syntax:

interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}

Java Interface Example

In this example, the Printable interface has only one method, and its implementation is provided in the
A6 class.

interface printable
{
void print();
}
class A6 implements printable
{
public void print()
{
System.out.println("Hello");
}

public static void main(String args[])


{
A6 obj = new A6();
obj.print();
}
}

Muslim Association College of Arts and Science Page 40


Programming in Java

Java Package
• A java package is a group of similar types of classes, interfaces and sub-packages.
• Package in java can be categorized in two form, built-in package and user-defined package.
• There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
• Here, we will have the detailed learning of creating and using user-defined packages.

Advantage of Java Package


1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.

Muslim Association College of Arts and Science Page 41


Programming in Java

The package keyword is used to create a package in java.

//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}

How to access package from another package?

• We can invoke package in our program Using packagename.*


• If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
• The import keyword is used to make the classes and interface of another package accessible to
the current package.

Example of package that import the packagename.*

STEP 1: Create Package

//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}

Muslim Association College of Arts and Science Page 42


Programming in Java

STEP 2: Call Package to Program

________________________________________
//save by B.java

package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:Hello

Muslim Association College of Arts and Science Page 43


Programming in Java

MODULE 3

Muslim Association College of Arts and Science Page 44


Programming in Java

Exception Handling in Java


• 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.
• In this page, we will learn about Java exceptions, its type and the difference between checked
and unchecked exceptions.

What is Exception in Java

• 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 ClassNotFoundException,


IOException, SQLException, RemoteException, 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.

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.

Muslim Association College of Arts and Science Page 45


Programming in Java

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.

Java Exception Handling Example

Let's see an example of Java Exception Handling where we using a try-catch statement to handle the
exception.

public class A
{
public static void main(String args[])
{
Try
{
//code that may raise exception
int data=100/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
//rest code of the program
System.out.println("rest of the code...");
}
}

Muslim Association College of Arts and Science Page 46


Programming in Java

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 RuntimeException and Error are known as
checked exceptions e.g. IOException, SQLException etc. Checked exceptions are checked at compile-
time.

2) Unchecked Exception

The classes which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Java Multi-catch block

A try block can be followed by one or more catch blocks. Each catch block must contain a different
exception handler. So, if you have to perform different tasks at the occurrence of different exceptions,
use java multi-catch block.

o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.

Let's see a simple example of java multi-catch block.

public class MultipleCatchBlock1


{

public static void main(String[] args)


{

Muslim Association College of Arts and Science Page 47


Programming in Java

try
{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
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.

Muslim Association College of Arts and Science Page 48


Programming in Java

class TestFinallyBlock
{
public static void main(String args[])
{
try
{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:
finally block is always executed
rest of the code...

Thread in java

A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of


execution.Threads are independent, if there occurs exception in one thread, it doesn't affect other
threads. It shares a common memory area.

Muslim Association College of Arts and Science Page 49


Programming in Java

As shown in the above figure, thread is executed inside the process. There is context-switching between
the threads. There can be multiple processes inside the OS and one process can have multiple threads.

Life cycle of a Thread (Thread States)

A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle in
javanew, runnable, non-runnable and terminated. There is no running state.

But for better understanding the threads, we are explaining it in the 5 states.

The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

Muslim Association College of Arts and Science Page 50


Programming in Java

1) New

The thread is in new state if you create an instance of Thread class but before the invocation of
start() method.

2) Runnable

The thread is in runnable state after invocation of start() method, but the thread scheduler has not
selected it to be the running thread.

3) Running

The thread is in running state if the thread scheduler has selected it.

4) Non-Runnable (Blocked)

This is the state when the thread is still alive, but is currently not eligible to run.

5) Terminated

A thread is in terminated or dead state when its run() method exits.

How to create thread

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

1. 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:

o Thread()
o Thread(String name)

Muslim Association College of Arts and Science Page 51


Programming in Java

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

Java Thread Example by extending Thread class

class Multi extends Thread


{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi t1=new Multi();
t1.start();
}
}
Output:thread is running...
________________________________________

2.Runnable interface:

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

1. public void run(): is used to perform action for a thread.

2) Java Thread Example by implementing Runnable interface

class Multi3 implements Runnable


{
public void run()
{
System.out.println("thread is running...");
}

public static void main(String args[])


{

Muslim Association College of Arts and Science Page 52


Programming in Java

Multi3 m1=new Multi3();


Thread t1 =new Thread(m1);
t1.start();
}
}
Output:thread is running...

Starting a thread:

start() method of Thread class is used to start a newly created thread. It performs following tasks:
o A new thread starts(with new callstack).
o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.

Next Topi

Muslim Association College of Arts and Science Page 53


Programming in Java

MODULE IV

Muslim Association College of Arts and Science Page 54


Programming in Java

API Packages
Java APl(Application Program Interface) provides a large numbers of classes grouped into different
packages according to functionality Following figure shows the system packages that are frequently
used in the programs.

Java System Packages and Their Classes

java.lang Language support classes. They include classes for primitive types, string, math functions,
thread and exceptions.

java.util Language utility classes such as vectors, hash tables, random numbers, data, etc.

java.io Input/output support classes. They provide facilities for the input and output of data.

java.applet Classes for creating and implementing applets.

java.net Classes for networking. They include classes for communicating with local computers as
well as with internet servers.

java.awt Set of classes for implementing graphical user interface. They include classes for windows,
buttons, lists, menus and so on.

Java I/O

Java I/O (Input and Output) is used to process the input and produce the output.

Java uses the concept of stream to make I/O operation fast. The java.io package contains all the classes
required for input and output operations.

We can perform file handling in java by Java I/O API.

Muslim Association College of Arts and Science Page 55


Programming in Java

Stream

A stream is a sequence of data.In Java a stream is composed of bytes. It's called a stream because it is
like a stream of water that continues to flow.

In java, 3 streams are created for us automatically. All these streams are attached with console.

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

OutputStream vs InputStream
OutputStream

Java application uses an output stream to write data to a destination, it may be a file, an array,
peripheral device or socket.

InputStream

Java application uses an input stream to read data from a source, it may be a file, an array, peripheral
device or socket.

OutputStream class

OutputStream class is an abstract class. It is the super class of all classes representing an output stream
of bytes. An output stream accepts output bytes and sends them to some sink.

Useful methods of OutputStream

Method Description
1) public void write(int)throws IOException is used to write a byte to the current output stream.
2) public void write(byte[])throws is used to write an array of byte to the current output
IOException stream.
3) public void flush()throws IOException flushes the current output stream.
4) public void close()throws IOException is used to close the current output stream.

Muslim Association College of Arts and Science Page 56


Programming in Java

OutputStream Hierarchy

InputStream class

InputStream class is an abstract class. It is the super class of all classes representing an input stream of
bytes.

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

Muslim Association College of Arts and Science Page 57


Programming in Java

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.

Muslim Association College of Arts and Science Page 58


Programming in Java

Frame

The Frame is the container that contain title bar and can have menu bars. It can have other components
like button, textfield etc.

AWT Example

Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing Button
component on the Frame.

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

Output

Muslim Association College of Arts and Science Page 59


Programming in Java

Java Swing
Java Swing tutorial is used to create window-based applications. It is built on the top of AWT (Abstract
Windowing Toolkit) API and entirely written in java.

Unlike AWT, Java Swing provides platform-independent and lightweight components.

The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Difference between AWT and Swing

There are many differences between java awt and swing that are given below.

No. Java AWT Java Swing

Java swing components are platform-


1) AWT components are platform-dependent.
independent.

2) AWT components are heavyweight. Swing components are lightweight.

3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.

Swing provides more powerful


components such as tables, lists,
4) AWT provides less components than Swing.
scrollpanes, colorchooser, tabbedpane
etc.

5) AWT doesn't follows MVC(Model View Controller) where Swing follows MVC.
model represents data, view represents presentation and

Muslim Association College of Arts and Science Page 60


Programming in Java

controller acts as an interface between model and view.

Event Handling in AWT


Change in the state of an object is known as event i.e. event describes the change in state of source.
Events are generated as result of user interaction with the graphical user interface components. For
example, clicking on a button, moving the mouse, entering a character through keyboard,selecting an
item from list, scrolling the page are the activities that causes an event to happen.

Types of Event

The events can be broadly classified into two categories:

• Foreground Events - Those events which require the direct interaction of user.They are
generated as consequences of a person interacting with the graphical components in Graphical
User Interface. For example, clicking on a button, moving the mouse, entering a character
through keyboard,selecting an item from list, scrolling the page etc.
• Background Events - Those events that require the interaction of end user are known as
background events. Operating system interrupts, hardware or software failure, timer expires, an
operation completion are the example of background events.

What is Event Handling?

Event Handling is the mechanism that controls the event and decides what should happen if an event
occurs. This mechanism have the code which is known as event handler that is executed when an event
occurs. Java Uses the Delegation Event Model to handle the events. This model defines the standard
mechanism to generate and handle the events.Let's have a brief introduction to this model.

The Delegation Event Model has the following key participants namely:

• Source - The source is an object on which event occurs. Source is responsible for providing
information of the occurred event to it's handler. Java provide as with classes for source object.
• Listener - It is also known as event handler.Listener is responsible for generating response to an
event. From java implementation point of view the listener is also an object. Listener waits until
it receives an event. Once the event is received , the listener process the event an then returns.

The benefit of this approach is that the user interface logic is completely separated from the logic that
generates the event. The user interface element is able to delegate the processing of an event to the
separate piece of code. In this model ,Listener needs to be registered with the source object so that the
listener can receive the event notification. This is an efficient way of handling the event because the
event notifications are sent only to those listener that want to receive them.

Steps involved in event handling

• The User clicks the button and the event is generated.

Muslim Association College of Arts and Science Page 61


Programming in Java

• Now the object of concerned event class is created automatically and information about the
source and the event get populated with in same object.
• Event object is forwarded to the method of registered listener class.
• the method is now get executed and returns.

Java JDBC
Java JDBC is a java API to connect and execute query with the database. JDBC API uses jdbc drivers to
connect with the database.

Why use JDBC

Before JDBC, ODBC API was the database API to connect and execute query with the database. But,
ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and unsecured).
That is why Java has defined its own API (JDBC API) that uses JDBC drivers (written in Java language).

Common JDBC Components

The JDBC API provides the following interfaces and classes –

Muslim Association College of Arts and Science Page 62


Programming in Java

• DriverManager: This class manages a list of database drivers. Matches connection requests from
the java application with the proper database driver using communication sub protocol. The first
driver that recognizes a certain subprotocol under JDBC will be used to establish a database
Connection.
• Driver: This interface handles the communications with the database server. You will interact
directly with Driver objects very rarely. Instead, you use DriverManager objects, which manages
objects of this type. It also abstracts the details associated with working with Driver objects.
• Connection: This interface with all methods for contacting a database. The connection object
represents communication context, i.e., all communication with database is through connection
object only.
• Statement: You use objects created from this interface to submit the SQL statements to the
database. Some derived interfaces accept parameters in addition to executing stored
procedures.
• ResultSet: These objects hold data retrieved from a database after you execute an SQL query
using Statement objects. It acts as an iterator to allow you to move through its data.
• SQLException: This class handles any errors that occur in a database application.

Muslim Association College of Arts and Science Page 63

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy