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

java (1)

The document provides an overview of Java programming, focusing on Object-Oriented Programming (OOP) concepts such as classes, objects, inheritance, and polymorphism. It details Java's features, including its compiled and interpreted nature, platform independence, and robustness, along with comparisons to C and C++. Additionally, it covers Java's environment, the structure of Java programs, operators, and arrays.

Uploaded by

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

java (1)

The document provides an overview of Java programming, focusing on Object-Oriented Programming (OOP) concepts such as classes, objects, inheritance, and polymorphism. It details Java's features, including its compiled and interpreted nature, platform independence, and robustness, along with comparisons to C and C++. Additionally, it covers Java's environment, the structure of Java programs, operators, and arrays.

Uploaded by

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

II sem BCA JAVA PROGRAMMING

JAVA PROGRAMMING

OBJECT-ORIENTED PROGRAMMING(OOPs):
An Object-Oriented is an approach for organizing and developing a program which eliminates the
drawbacks with a traditional conventional programming.
Features of Object Oriented Programming:
 In OOP the main focus is an object.
 In OOP a programs are decomposed into an objects.
 In OOP data is secured.
 In OOP employ’s the bottom of programming design.
 In OOP objects communicate with each other through a method (functions).

OOPs Concepts:
 Objects
 Class
 Abstraction
 Encapsulation
 Dynamic Binding
 Inheritance
 Message & Communication
 Polymorphism

1. Object:
An object is an abstraction of a real world of entity. It may represent Person, place, an icon,
windows etc., an object is a group of “data and a method”.
An object is an “instance of a class”.
2. Class:
Class is a user-defined data types. It consist of data members and
Member function (method) that manipulates these data.
For ex: - Lotus, rose are the members of the class called a flowers.
3. Abstraction:
It is defined as a separation of unnecessary details or explanation from the
System requirements, so as to reduce the complexity of understanding the system requirements.
4. Encapsulation:
Encapsulation is a mechanism that puts in capsule (pack) that data and a function together. It is a
result of hiding the implementation of details of objects from its user.
5. Polymorphism:
Polymorphism having many forms. A single entity can take more than one form.
For ex: - A polymorphism can be implemented by “Method overloading” or “function overloading”.
E.g.:- into add (), float add (), double add ().

6. Dynamic Binding:
Dynamic binding means that the code associated with a given procedure call is not known until the
time of call at “run time”.
7. Inheritance:
Inheritance is the process in which the object of one class acquires the properties of
object of another class.
8. Message and Communication:
Objects are communicated with each other by sending and receiving a messages.
II sem BCA JAVA PROGRAMMING

Obj 1

Obj Obj
2 3

Obj
4
Java Programming:
Java is a general purpose pure OOP language developed by Sun Microsystems of USA
in 1991. It is originally called as “OAK” by James Gosling is the inventor of Java programming.

Features of Java:
 Compiled and Interpreted
 Platform-Independent and Portable
 Object-oriented
 Robust and Secure
 Distributed
 Familiar, Simple and Compact
 Multithreaded and Interactive
 High Performances
 Dynamic and Extensible

1. COMPILED AND INTERPRETED:-


Usually a computer language is either compiled or interpreted. Java
Combines these approaches thus making Java a two-stage system. First java compiler translates source
code into what is known as byte code instructions. Byte codes are machine instructions and therefore,
in the stage. Java interpreter generates source code into that can be directly executed by the machine
that is running the Java program. We can thus say that Java is both a compiled and an interpreted
language.

2. PLATFORM-INDEPENDENT AND PORTABLE:-


The most significant contribution of java over other languages is its
Portability. Java programs can be easily moved from one computer system to another, anywhere and
anytime. Changes in upgrade in operating system, processors and system resources will not force any
changes in the Java programs. This is the reason why Java has become a popular language for
programming for Internet which interconnects different kinds of system worldwide.

3. OBJECT-ORIENTED:-
Java is a true object-oriented language. Almost everything in Java is
an object. All program code and data reside within the objects and classes. Java comes with an
extensive set of classes, arranged in a packages that can be used in our programs be inheritance. The
object model in Java is simple and easy to extend.

4. ROBUST AND SECURE:-


Java is a robust language. It provides many safeguards to ensure
reliable code. It has strict compile time and run time checking for data types. It is designed as a garbage
– collected language relieving the programmers virtually of all memory management problems. Java
also incorporates the concept of exception handling which captures serious errors and eliminates any
risk of crashing the system.
Security becomes an important issue for a language that is used for programming on internet.
II sem BCA JAVA PROGRAMMING
5. DISTRUBUTED:-
Java is designed as a distributed language for creating applications on networks. It has
ability to share both data and programs. Java applications can open and access remote objects on
Internet as easily as they can do in a local system. This enables several computers working together on a
network.

6. SIMPLE, SMALL AND FAMILIAR:-


Many features of C and C++ that are either redundant or source of
Unreliable mode is not part of Java. Java does not use pointers, preprocessor header files, into statement
and many others. It also eliminates operator overloading and multiple inheritance. Hence java is simple.

7. MULTITHREADED AND INTERACTIVE:-


Multithreaded means handling multiple tasks simultaneously. Java supports
Multithreaded programs. This means that we need not wait for the application to finish one task before
beginning another.

8. HIGH PERFORMANCES:-
Java performance is impressive for an interpreted language, mainly due to the
Use of intermediate byte code. Java architecture is also designed to reduce overheads during runtime.
Further, the incorporation of multithreading enhances the overall speed of Java programs.

9. DYNAMIC AND EXTENSIBLE:-


Java is a dynamic language. Java is capable of dynamically_linking in new class
Libraries, methods, and objects.
Java programs support functions written in other languages such as C and C++. These functions
are known as native methods. Native methods are linked dynamically at runtime.

BYTE CODE:-
A Java compiler translates/converts Java source code into what known as “Byte Code”. Byte
code is not machine instruction code.

DIFFERENCE B/W C AND JAVA PROGRAMMING:

C JAVA

1. Procedural-Oriented programming language. 1. Pure object oriented programming language


2. C was developed by “Dennis Ritchie” in 1972.2. Developed by “James Gosling” in 1991.
3. It is compiled only. 3. It is both compiled and interpreted.
4. It has a header file. 4. No header files.
5. It supports pointers. 5. It does not support pointer.
6. It has keyword like sizeof, goto, auto, extern, 6. No such keywords.
Typedef.
7. Data types-struct, union of enum. 7. No such data types.
8. It supports global variables. 8. No global variables.
9. It does not allow/use labeled like break, 9. It uses labeled break, continue statements.
Continue statement.
10. It doesn’t add features of OOP’s 10. It adds many features of OOP’s
11. No instances of >>>operator. 11. Instances of >>>operator.
12. It has a const keyword for constant 12. Constants is replaced by final keyword e.g.:- const
int a=10; for variable.
E.g.:- final int a=10;

DIFFERENCE B/W C++ AND JAVA:-


II sem BCA JAVA PROGRAMMING

C++ JAVA

1. Its C with object oriented extension. 1. Its pre-object oriented programming


Language.
2. Its develop by Stroustrup in 1980 2. Its developed by James Gosling in 1991.
3. Its compiled only. 3. Its both compiled and interpreted
4. It has header files. 4. No header files.
5. It supports pointers. 5. No pointers.
6. It supports global variable. 6. It doesn’t supports global variable.
7. It supports operator overloading. 7. It doesn’t supports operator overloading.
8. It supports multiple inheritance. 8. It doesn’t supports multiple inheritance.
Multiple inheritance is implemented using
“interface”.
9. It supports destructor. 9. Destructor function is used to finalize( )
Method
10. It supports virtual functions 10. Virtual function is replaced by overridden
Method.
11. It supports template class. 11. It doesn’t have template class.
12. It has const keyword. 12. Const is replaced by final.
13. It doesn’t use labeled break and continue 13. It has labeled break and continue
Statements

Java Environment:-
Java Development kit(JDK)
Tools:-

 Javac :- Java compiler.


 Java:- Interpreter.
 Applet viewer:-for viewing applet.
 Javadoc:-for creating an HTML document.
 Jdb:- Java debugger

Hundred number of class and method are part of Java Standard Library(JSL) also
known as Application Programming Interface(API).
Language package, utilities package, input/output package, networking package, AWT package, Applet
package.
Overview of Java:-

 Standard alone applets.


 Web applets.

Java source code

Java
compiler

Java Java
enabled web interpreter
browser
II sem BCA JAVA PROGRAMMING

JAVA VIRTUAL MACHINE(JVM):

Java program Java compiler Virtual machine

Byte code Java interpreter Machine code

Virtual machine real machine

 Compiled
 Interpreted

A Java compiler produces an intermediate code called as byte code for an


machine doesn’t exist. The machine is called Java virtual machine & it exists only inside the computer
memory. Java Virtual Machine- it is a stimulated computer within the computer & it does all the main
function of real computer.
The process of compiling the Java program into a byte code which is also known as
“virtual Machine Code”. The VMC are not machine specific code is generated by the Java interpreter
which acts as an intermediate between the virtual machine and the real machine.

GENERAL STRUCTURE OF A JAVA PROGRAM:-

Documentation section

Package Statements

Import Statement

Interface Statement

Class Definition
Main method class
{
Body of main method
II sem BCA JAVA PROGRAMMING

Eg:- class simple


{
public static void main(string args[ ])
{
System.out.println(“java is better than C++”);
}
}

public:-
The keyword public is a member access specifier that declares that the main method is
unprotected & making it accessible to all other classes.

static:-
The keyword static declares that the method has one that belongs to the entire class and not a
part of any object of the class. The main method is always declared as static since the Java interpreter
uses this method before any objects are created.

void:-
It states that the main method doesn’t return any value but it simply displays some text on the
screen.

Strings args[ ]:-


Strings arrays[ ] declares a parameter named arguments which contains an array of objects of
the class type string.
System.out.println:-
Println method is a member of out object which is static data member of system class.
e.g:-
write a Java program to find the sum of twonumbers:-

import java.io.*;
class sum
{
Public static void main(string args[]) throws IOE exception
{
int n1,n2,sum;
DataInputStream d=new Data InputStream(System.in);
System.out.println(“enter first number”);
n1=Integer.parseInt(d.readLine());
system.out.println(“enter second number”);
n2=Integer.parse Int (d.readLine());
sum=n1+n2;
system.out.println(“Sum is :”+sum);
}
}

Java tokens:_
 Reserved words(keywords)
 Identifier
 Literals
 Separators
 operators
II sem BCA JAVA PROGRAMMING

Operators:
An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations.
Java operators can be classified as follows..
1. Arithmetic operators: java provides all the basic arithmetic operators. The arithmetic operators
are
+ Addition/unary plus
- Subtraction/unary minus
* Multiplication
/ Division
% Modulo division
2. Relational operators: Relational operators are used to perform two quantities depending on their
relation. Relational operators are
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
= = is equal to
!= is not equal to
3. Logical operators: Logical operators are used to two or more relational expressions. Java has three
logical operators.
&& logical AND
|| logical OR
! logical NOT
4. Assignment operators: Assignment operators are used to assign the value of an expression to a
variable, ‘ = ’used as an assignment operator.
i.e. a = 5;
5. Increment and decrement operators: Increment operator ++ increment the value of operand by 1
where as decrement operators -- decrease the operand by 1.
6. Conditional operators: This operator is used to construct conditional expression in the form of
exp1 ? exp2 : exp3
if exp1 is true then exp2 is evaluated else exp3 is evaluated.
7. Bitwise operators: These operators are used for testing the bits of shifting the them to the right or
left.
& bitwise AND
! bitwise OR
^ bitwise exclusive OR
<< shift left
>> shift right
>>> shift right with zero fill
8. Special operators: java supports two special kinds of operators such as
Instanceof operator : this operator allows us to determine whether the object belongs to a particular
class or not
For Example: person instanceof student
is true if the object person belongs to the class student; otherwise it is false.
Dot operator: The dot operator(.) is used to access the instance variables and methods of class objects.
Example: person. age // reference to the variable age
Person. salary( ) // reference to the method salary( )

ARRAYS in Java:
An array is a group of contiguous or related data items that share a common name.
One-Dimensional Array:
A list of items can be given one variable name using only one subscript and such a variable is
called a one dimensional array.
II sem BCA JAVA PROGRAMMING
Creation of Arrays: java allows us to create an arrays using new operator only.
Syntax: Arrayname = new type[size];
Example: number = new int [5];
Here, The variable number refers to an array of 5 integers.
Initialization of Arrays: The process of giving an values into an array is called initialization. This is
done using the array subscript as follows..
Arrayname [subscript ] = value;
i.e. number[0] = 10;
number[1] = 20;
………………
Number[4] = 50;
Arrays starting with a subscript of 0 and ends with a value one less than the size specified.
We can also initialize arrays automatically using this syntax
Type arrayname[ ] = { list of values };

Exa: int number [ ] = { 10, 20, 30, 40, 50};

Two-Dimensional Arrays:
Unlike one dimensional array is having only one dimension, two dimensional array as two dimension
in order represent array elements.
Creation of two-dimensional arrays as
Syntax: type arrayname [ ] [ ]
arrayname = new type[size1] [size2];
OR
type arrayname [ ] [ ] = new type[size1] [size2];

Example: int matrix = new int [3][3];


Each dimension of array is indexed from zero to its maximum size minus one. First index selects the
row and the second index selects the columns.
Matrix is an example for two-dimensional array.
We can initialize two-dimensional array with a list of initial values enclosed in braces..
Int table [2][3] = {0,0,0,1,1,1};
Initializes the elements of the first row to zero and the second row to one.
Another way to initialize two-dimensional array is to use of nested for loops..
for ( i = 0; i < 3 ; i++)
{
for (j = 0; j < 3 ; j++)
{
if ( i = = j)
table [i] [j] = 1;
else
table [i] [j] = 0;
}
}

Output: 1 0 0
0 1 0
0 0 1

Control or Decision making Statements in Java:


Java language provides different decision making statements. They are..
1. if statement
2. Switch statement
II sem BCA JAVA PROGRAMMING
1. if Statement : The if statement is a powerful decision making statement. its used to control the
flow of execution of statements. The different forms of if statements are..
Simple if Statement:
The general form of simple if statement is
If ( test expression )
{
Statement-block;
}
Statement-x;
Explanation: If the test expression is true , the statement-block is executed, otherwise execution will
jump to the statement-x.
Example:
………………………
If ( category = =sports)
{
Marks = marks + bonus_marks;
}
System.out.println(marks);
The if.. else statement:

The general form of simple if-else statement is


If ( test expression )
{
True-block Statement(s);
}
else
{
False-block statement(s);
}
Statement-x;
Explanation: if test expression is true, then true-block statement(s) is are executed ,otherwise false-
block statement(s) are executed.
Example: …………….
if(num % 2 = = 0)
System.out.println(“Number is even”);
else
System.out.println(“Number is odd”);
………………
Nesting of if. else statement:
One if-else statement is enclosed within another is called nested if. else
Syntax:
if ( test condition 1 )
if (test condition 2)
Statement-1;
else
Statement-2;
else
if(test condition 3)
Statement-3;
else
Statement-4;

Explanation: if both test condition 1 and test condition 2 are true then statement 1 is executed, if test
condition 1 is true , test condition 2 is false statement 2 is executed. If test condition1 is false but test
condition 3 is true then statement 3 is executed. when both test condition 1 and test condition 3 are false
then statement 4 is executed.
Example: …………………
II sem BCA JAVA PROGRAMMING
if ( A > B)
{
if (A > C)
System.out.println( “ A is larger”);
else
System.out.println( “ C is larger”);
}
else
{
if (B > C)
System.out.println( “ B is larger”);
else
System.out.println( “ C is larger”);
}
……………………………..

Switch or Multiway Decision Statement:


Java has a built-in multiway statement known as a Switch. The switch statement tests the value of
a given variable(or expression) against a list of case values and when a match is found, a block of
statements associated with that case is executed. if none of the case label values match then default
block is executed. the general form of switch statement is..

Switch(expression)
{
case value-1 :Statement block-1;
break;
case value-2 : Statement block-2;
break;
…………….
…………….
default : default-block;
break;
}
Statement;
Example: ………………………
Switch(dayno)
{
case 1 : System.out.println(“Sunday”);
break;
case 2 : System.out.println(“Monday”);
break;
……………………….
case 7 : System.out.println(“Saturday”);
break;
default : System.out.println(“invalid day number);
break;
}

Strings:
String is a sequence of characters. In java strings are class objects and implemented using two
classes namely String and StringBuffer.
A java string is an instantiated object of the string class.
Strings in java are not character array and is not NULL terminated.
Strings may be declared and created as follows..
Syntax:
II sem BCA JAVA PROGRAMMING
String stringname;
stringname = new String (“String”);
Example:
String firstname;
firstname = new String (“H D SURENDRA”);
These two statements may be combined as follows..
String firstname = new string (“H D SURENDRA”);
Java strings can be concatenated using the + operator.
Example:
String fullname = name1 + name2;
String fullname = “COMPUTER” + “SCIENCE”;
String Methods:
The String class defines a number of methods that allow us to accomplish a variety of string
manipulation tasks.

Method call Task performed


s2 = s1.toLowerCase( ) converts the string s1 to all lowercase
s2 = s1.toUpperCase( ) converts the string s1 to all Uppercase
s1.equals(s2) returns true if s1 equal to s2
s1.equalsIgnoreCase(s2) returns true if s1 =s2. ignoring the case of characters
s1.length( ) gives the length of s1
s1.concat(s2) concatenates s1 and s2
s1.substring(n) gives the substring starting from nth character

StringBuffer Class:
StringBuffer is a peer class of string. While string creates string of fixed-length, StringBuffer
creates string of flexible length that can be modified in terms of both length and content.
Commonly used stringbuffer Methods are..

Method Task
s1.setChartAt(n, ‘x’) Modifies the nth character to x
s1.append(s2) appends the string s2 to s1 at the end
s1.insert (n, s2) Inserts the string s2 at the position n of
the string s1.

Looping Statements in java:

The process of repeatedly executing a block of statements is known as looping.


Java supports three kinds of looping statements.
The While Statement
The while statement is also called as Pre-tested looping statement.
Syntax:
while( test condition)
{
Statement 1;
Statement 2;
……….…….
}
Statement-x;
In this structure the checking of a condition is done at the beginning. The set of statements in
the block are executed again and again until the test condition is true. If the test condition becomes
false control is transferred out of the structure.

Example:
II sem BCA JAVA PROGRAMMING
Sum =0;
count =1;
while( count<100)
{
sum= sum + count;
count ++;
}
System.out.println(“ Total sum = “ +sum);

The do-while Statement:


This structure is also called post-tested looping statement. because checking of the condition is
done at the end.
Syntax:
do
{
Statement 1;
Statement 2;
……….…….
}while(test condition);
Statement-x;
The set of statements in the block are executed again and again until the test condition is true. If the
test condition becomes false control is transferred out of the structure.
Example:
prod = 1;
count = 1;
do
{
prod = prod * count;
count++;
}while(count< =100)
System.out.println(“Total product = “ + prod);

The for Statement:


for statement is also called as fixed execution structure.
Syntax:
for( initialization; test condition ; increment/ decrement)
{
Body of the loop
}
Initialization of control variable is done at first,, i.e.i = 1 or count = 0
The value of the control variable is tested using the test condition i<10. if its true body of the loop is
executed otherwise loop is terminated.
After this control variable is incremented i.e. i++. Again test condition is evaluated to execute the
body of the loop. This process continues till control variable fails to satisfy the test condition.
Example: …………………
for( i = 1; i < 10; i++)
System.out.println( i );
…………………….

Nesting of for loops:


One for statement within another for statement is called nesting of for loops.
Example: ………………
for( i =1; i < m ; i++)
{
for( j= 1; j <n; j++)
II sem BCA JAVA PROGRAMMING
{
x = m * n;
System.out.println( “ “ + x);
}
System.out.println( “ “ );
}

Break and Continue Statements:


The break statement is used to terminate loops. It can be used to within a while, do-while, or for
statement. The break statement is simply written as :
while(……) do
{ {
……….. ………………
Break; break;
…………. …………………
} }while(….)
next-statement; next-statement;
when break is encountered inside any loop control automatically comes out of the loop.
The continue statement can be used to within a while, do-while, or for statement. The continue
statement is simply written as :
while(……) do
{ {
……….. ………………
continue; continue;
…………. …………………
} }while(….)
next-statement; next-statement;
when continue is encountered inside any loop control automatically passes to the beginning the
loop.

Access Specifiers:
Private: A variable or method are declared as private, they are accessible only within their own
class. They cannot be inherited by subclass and therefore not accessible in subclass. A method
declared as private prevents the method from being subclassed. Private filed is the highest degree of
protection.
Example:
private int number;
private void sum( )
{ ……………………..}
Public: A variable or method declared as public visible to the entire class, outside the class and
accessible everywhere.
Example:
public int number;
public void sum( )
{ ……………………..}
friendly:
unlike public access makes fields visible in classes, regardless of their packages while the
friendly access makes fields visible only in the same package, but not in other packages.
Protected:
The protected field lies in between the public access and friendly access. i.e. the
protected makes the fields visible not only to all classes and subclasses in the same package but also
to subclasses in other packages.
II sem BCA JAVA PROGRAMMING

Class and Objects


Class:
A class is a user-defined data type that provide a convenient method for packing together a group
of logically related data items and functions that work on them.
In Java, the data items are called fields and the functions are called methods.
A class defines the state and behaviour of the basic program components known as objects. classes
create objects and objects use methods to communicate between them.

DEFINING A CLASS:

The basic form of class definition is:


class classname [extends superclassname]
{
[ variable declaration; ]
[methods declaration; ]
}
Classname and superclassname are any valid Java identifiers. The keyword extends indicates that the
properties of the superclassname class are extended to the classname class. No semicolon after closing
brace .
Example:
class Rectangle
{
int length; //declaration of variables
int width;

void getdata (int x , int y) // definition of method


{
length = x;
width = y;
}

int rectarea( ) //definition of another method


{
int area = length * width;
return(area);
}
}
The class Rectangle contains two integer type instance variables length and width are also known as
member variables.
The getdata( ) method is basically added to values to the instance variables length and width. x and
y are two parameters for the instance variables. The getdata( ) has a return type of void because it does
not return any value.
The new method rectarea( ) computes area of rectangle and returns the result would be an integer,
the return type of the method has been specified as int.
Creating Objects:
An object in java is essentially a block of memory that contains space to store all the instance
variables. Creating an object is also called as instantiating object.
II sem BCA JAVA PROGRAMMING
Objects in java are created using new operator. The new operator crates an object of the specified
class and returns a reference to that object.
Example:
Rectangle rec1; // declare
rect1 = new rectangle ( ) ; // instantiate
Both statements can be combined as
Rectangle rect1 = new Rectangle( );

Accessing Class Members:


In order to access instance variables and methods directly, we must use the object and the dot
operator as shown below..
Objectname. Variablename
Objectname. Methodname(parameter-list);
Examples:
rect1.length;
rect1. rectarea( );

Application of Class and object:


class Rectangle
{
int length; //declaration of variables
int width;

void getdata (int x , int y) // definition of method


{
length = x;
width = y;
}
int rectarea( ) //definition of another method
{
int area = length * width;
return(area);
}
}

// Main program for the above class definition Rectangle


Class Rectarea
{
public static void main ( String args[ ])
{
Rectangle rect = new Rectangle ( ); // Creating an object
rect.getdata(10,20); // Accessing method
int area = rect.rectarea( ); // Calling rectarea
System.out.println(" Area = " + area);
}
}

Output: area = 200


II sem BCA JAVA PROGRAMMING

Access Modifiers:
Final variables and methods:
All methods and variables can be overridden by default in subclasses. If we want to prevent the
subclasses from overriding the members of the superclass, we can declare them as final using the
keyword final as a modifier. Example:
final int SIZE = 100 ;
final void showstatus( ) { ………….. }
Final Class:
A class that cannot be subclassed is called a final class. This is achieved in Java using the keyword
final as follows:
final class Aclass { ……………}
final class Bclass extends Someclass { ………….}
declaring a class final prevents any unwanted extensions to the class.

Static members:
The members that are declared using the keyword static are called static members. A variables in a
class are declared as static are called as static variables. And a method in a class are declared as static
are called as static methods.
Example:
static int count;
static int max(int x, int y);
static members are common to all the objects and accessed without using a particular object. i.e.
the member belongs to the class as a whole rather than the objects created from the class.
static variables are used when we want to have a variable common to all instances of a class. Java
creates a only one copy for a static variable which can be used by all the objects.

Static methods restrictions:


 They can only call other static methods
 They can only access static data
 They cannot refer to this or super in any way

Abstract Methods and Classes:


We declare a method as final that method is not redefined in a subclass. i.e. the method can never
be subclassed. Java allows us to do something that is exactly opposite to this. i.e. we can indicate that a
method must always be redefined in a subclass, thus making overriding compulsory. This is done using
the modifier keyword abstract in the method definition. Example:
abstract class Shape
{
……………..
……………..
abstract void draw( };
……………….
}
While using abstract class, we follow the conditions
 We cannot use abstract classes to instantiate objects directly
Exa: shape s = new shape( ); is illegal because shape is abstract class
 The abstract methods of an abstract class must be defined in its subclass
 We cannot declare abstract constructors.

Native :
Volatile:
II sem BCA JAVA PROGRAMMING
Synchronized:
Introduction to Methods:
In Java, the data items in a class are called fields and the functions are called method.
Methods are necessary for manipulating the data contained in the class. Methods are declared inside
the body of the class after the declaration of instance variables. The general form of a method
declaration is.
Syntax:
type methodname (parameter-list)
{
method-body;
}
Method declarations have four basic parts:
 The name of the method (methodname)
 The type of the value the method returns (type)
 A list of parameters (parameter-list)
 The body of the method

The type specifies the type of value the method would return.
Methodname is a valid identifier. The parameter list is always enclosed in parentheses. The body
actually describes the operations to be performed on the data.
Example:
void getdata (int x , int y) // definition of method {
length = x;
width = y;
}
Constructors
Java supports a special type of method called a constructor, that enables an object to initialize itself
when it is created.
Characteristics of constructors are
 Constructors have the same name as that of the class
 They do not specify a return type, not even void.
 Constructors can be overloaded
Application of constructor..
class Rectangle
{
int length, width;

Rectangle (int x , int y) // defining costructor


{
length = x;
width = y;
}
int rectarea( )
{
int area = length * width;
return(area);
}
}

// Main program for the above class definition Rectangle


Class Rectarea
{
public static void main ( String args[ ])
{
Rectangle rect = new Rectangle(15,10);
//calling constructor
int area = rect.rectarea( ); // Calling rectarea
II sem BCA JAVA PROGRAMMING
System.out.println(" Area = " + area);
}
}

Output: area = 150

Methods Overloading
Two or more methods that have the same name, but different parameter lists and different definitions
are called methods overloading.
Methods overloading is used when objects are required to perform similar tasks but using different
input parameters.
Example:
class Room
{
float length, breadth;
Room (float x, float y) // Constructor 1
{
length = x;
breadth = y;
}
Room (float x) // Constructor 2
{
length = breadth * x;
}
Command line arguments:
Command line arguments are parameters that are supplied to the application program at the time of
the invoking it for execution.
We can write java programs that can receive and use the arguments provided in the command line.
Consider the main( ) method used in the java program
public static void main (String args[ ] )
here, args is described as an array of strings known as string objects. Any arguments provided in
the command line (at the time execution )are passed to the array args as its elements.
For example , consider the command line
java test C C++ JAVA Vb
this command line contains four arguments. These are assigned to the array args as follows..
C -------- args [0]
C++ -------- args[1]
JAVA ------- args[2]
Vb ------- args[3]
The individual elements of an array are accessed by using an index or subscript like args[ i ] .
For example args [2] denotes the third element and represent JAVA.

Inheritance
Reusability is one of the important aspect of OOP paradigm. if we could reuse something that
already exists rather than creating the same all over again. Java supports this concept. This is basically
done by creating new classes, reusing the properties of existing ones. The mechanism of deriving a new
class from an old one is called inheritance.
The old class is known as the base class or super class or parent class and the new one is called the
subclass or derived class or child class.
The inheritance allows subclasses to inherit all the variables and methods of their parent classes.
Inheritance may take different forms:
1. Single inheritance (only one super class)
2. Multiple inheritance (several super classes)
3. Hierarchical inheritance (one super class, many subclasses)
4. Multilevel inheritance (Derived from a derived class)
II sem BCA JAVA PROGRAMMING
Defining a Subclass:
A subclass is defined as follows:
class subclassname extends superclassname
{
Variable declaration;
Methods declarations;
}
The keyword extends signifies that the properties of the superclassname are extended to the
subclassname. The subclass will now contain its own variables and methods as well those of the super
class.

Single inheritance (only one super class):


In single inheritance only one base or super class and all its features are inherited to its subclass or
derived class. It establishes the relationship between the father and son.

Example:
class Room
{
int length, breadth;
Room (int x , int y)
{
length = x;
breadth = y;
}
int area( )
{
return(length * breadth);
}
}

Class Bedroom extends Room // Inheriting Room


{
int height;
BedRoom (int x, int y, int z)
{
Super(x,y); // pass values to superclass
height = z;
}
int volume( )
{
return( length * breadth * height);
}
}
class inherit
{
II sem BCA JAVA PROGRAMMING
public static void main ( String args[ ])
{
BedRoom = room1 = new Bedroom (14,12,10);
int area1 = room1.area( ); //superclass method
int volume1 = rooom1.volume ( ); //baseclass method
System.out.println(" Area1 = " + area1);
System.out.println(" Volume1= " + volume1);
}
}
Output:
Area1 = 168
Volume1 = 1680
The program defines a class Room and extends it to another class BedRoom. The subclass
BedRoom now includes three instance variables, namely, length, breadth and height and two methods,
area and volume.
The constructor in the derived class uses the super keyword to pass values that are required by the base
constructor.

Super keyword: Subclass Constructor


A subclass constructor is used to construct the instance variables of both the subclass and the
superclass. The subclass constructor uses the keyword super to invoke the constructor method of the
superclass. The keyword super is used subject to the following conditions.
 super may only be used within a subclass constructor method
 The call to superclass constructor must appear as the first statement within the subclass
constructor
 The parameters in the super call must match the order and type of the instance variable declared
in the superclass.

Multilevel Inheritance
A common requirement in object-oriented programming is the use of a derived class as a super
class. Java supports this concept and uses it extensively in building its class library. This concept
establishes grandfather-father- child relationship as shown below.
The class A serves as a base class for the derived class B which in turn serves as a base class for the
derived class C. The chain ABC is known as inheritance path.
A derived class with multilevel base classes is declared as follows.
class A
{
…………….
…………….
}
Class B extends A // first level
{
……………….
………………
}
Class c extends B //second level
{
……………..
……………..
}

Father Child
Grandfather
II sem BCA JAVA
PROGRAMMING

Superclass

Intermediate
superclass

Subclass
II sem BCA JAVA
PROGRAMMING

Packages and Interfaces


Package:
Packages are java’s way of grouping a variety of classes and/or interfaces
together. The grouping is usually done according to functionality. i.e. packages act as
"containers" for classes.
The concept of packages is similar to "class libraries" in other languages.
By organizing classes into packages we achieve the following benefits:
 The classes contained in the packages of other programs can be easily reused.
 In packages, classes can be unique compared with classes in other packages. i.e.
two classes in two different packages can have the same name.
 Packages provide a way to "hide" classes thus preventing other programs or
packages from accessing classes that are meant for internal use only.
 Packages also provide a way for separating "design" from "coding". First we can
design classes and then we can implement the Java code needed for the methods.

Types of packages:
Java packages are classified as two types
1) Java API packages
2) user defined packages

1) Java API packages:


Java API provides a large number of classes grouped into different packages according to
functionality.
Most of the time we use the packages available with the frequently used API packages are
listed below..

Package name Contents


Java . lang They include classes for primitive types, strings, math functions,
threads and exceptions.

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


numbers, date, etc.
java.io They provide facilities for the input and output of data.
java.awt They include classes for windows, buttons, lists, menus and so on.
java.net They include classes for communicating with local computers as
well as with internet servers.
java. applet Classes for creating and implementing applets.

Importing packages:
we can use many of the classes contained in a package, using import statements .and must
appear at the top of the file, before any file declarations. We may a follows:
Syntax:
import packagename.classname;
or
import packagename.*;
II sem BCA JAVA
PROGRAMMING
The first statement allows the specified class in the specified package to be
imported. For example:
import java,awt.Color;
imports the class Colour and therefore the class name can now be directly used in the
program. There is no need to use the package name to qualify the class.
The second statement imports-every class contained in the specified package. For
example, the statement
import java.awt.*;
will bring all classes of java.awt package.
2)User defined packages:
Java allows us to create our own packages, by declaring the name of the package using
the package keyword followed by the package name.
Syntax:
Package firstpackage; // package declaration
public class firstclass // class definition
{
……………..
……………. //body of the class
}
Here, the package name firstpackage . The class firstclass is now considered a part of this
package.
Creating our own package involves the following steps..
 Declare the package at the beginning of a file using the form package
packagename;
 Define the class that is to be put in the package and declare it public.
 Create a subdirectory under the directory where the main source files are stored.
 Store the listing as the classname.java file in the subdirectory created.
 Compile the file. This creates .class file in the subdirectory.
Using a package:
Consider a package named package1 containing a single class classA.
Package package1;
Public class classA
{
Public void displayA( )
{
System.out.println(“Class A”);
}
}
This source file should be named ClassA.java and stored in the subdirectory package 1.
ClassA.class will be stored in the same subdirectory.
Now consider the listing shown below:
import package1.ClassA;
class PackageTest1
{
public static void main (String args[ ] )
{
ClassA objectA = new ClassA( ) ;
objectA.displayA( );
}
}
II sem BCA JAVA
PROGRAMMING
This listing shows a simple program that imports the class ClassA from the package
package 1.
let us consider another package named package2 containing again a single class as
shown below:
package package2;
public class ClassB
{
protected int m = 10;
public void displayB( )
{
System.out.println("Class B);
System.out.println("m = " + m);
}
}
Here, the source file and the compiled file of this package are located in the subdirectory
package2.

Importing classes from other packages

import package1.ClassA;
import package2.*;
class PackageTest2
{
public static void main (String args[ ])
{
ClassA objectA = new ClassA( );
ClassB objectB = new ClassB( );
objectA.displayA( );
objectB.displayB( );
}
}
This program may be saved as PackageTest2.java, compiled and run to obtain the results.
The output will be
Class A
Class B
m = 10
When we import multiple packages it is likely that two or more packages contain classes
with identical names.
Example:
package pack1;
public class Teacher
{ ••••• ••• }
public class Student-
{……….. }
Package pack2;
Public class courses
{…………….}
Public class student
{…………………}
Now import and use these packages as
import pack1.*;
II sem BCA JAVA
PROGRAMMING
import pack2.*;
pack1.student student1; // create a student object
pack2.student student 2;
teacher teacher1;
courses course1;
output: class B
m = 10
class C
m = 10
n = 20

Access Protection:

Access
modifier Public Protected Friendly Private Private
(default) Protected
access
location
Same class Yes Yes Yes Yes Yes

Subclass in same class Yes Yes Yes Yes No

Other classes in same Yes Yes Yes No No


package

Subclass in other Yes Yes No Yes No


packages

Non-subclasses in other Yes No No No No


packages

Interfaces:
The concept of multiple inheritance in C++ can be implemented in java by using on of the
approach called interface.
An interface is basically a kind of class. Like classes, interfaces contain methods
and variables· the major difference. is, an interfaces define only abstract methods and
final fields. i.e. it doesn’t specify any code to implement these methods and data fields
contain only constants.
The general form of an interface definition is:

interface InterfaceName
{
variables declaration;
methods declaration;
}
Here, interface is the key word and InterfaceName is any
valid Java variables. Variables are declared as follows:
II sem BCA JAVA
PROGRAMMING

static final type VariableName = Value;

Methods declaration will contain only a list of methods without


any body statements. Example:

return-type methodNamel (parameter_list);


example of an interface definition that contains two variables
and one method
interface Item
{
static final int x= 10;
static final string name = “H D SURENDRA”;
void display( );
}
Extending interface:
Like classes, interfaces can also be extended. i.e. an interface can be subinterfaced from
other interfaces. The new subinterface will inherit all the members of the superinterface in
the manner similar to subclasses. This is achieved using the keyword extends as follows.
interface name2 extends name1
{
body of name2
}
For example,
interface ItemConstants
{
int code = 1001;
string name = “H D SURENDRA”;
}
interface Item extends ItemConstants
{
void display ( );
}
The interface Item would inherit both the constants code and
name into it.

IMPLEMENTING INTERFACES :
Interfaces are used as "superclasses" whose properties are inherited by classes. It is
necessary to create a class that inherits the given interface. This is done as follows:

class classname implements Interfacename


{
body of classname
}
Here the class classname "implements" the interface interfacename.

The more general form of implementation as follows.

class classname extends superclass


implements interfacel, interface2,……….
II sem BCA JAVA
PROGRAMMING
{
body of classname
}
This shows that a class can extend another class while implementing interfaces.
When a class implements more than one interface, they are separated by a comma.
Example:
In this program, first we create an interface Area and implement the same in two different
classes, Rectangle and Circle. We create an instance of each class using the new operator.
Now, we assign the reference to the Rectangle object rect to area. When we call the
compute method of area, the compute method of rectangle class is invoked.

// interfacetest.java
interface area /interface defined
{
final static float pi = 3.14F;
float compute (float x, float y);
}
class rectangle implements area //interface implemented
{
Public float compute (float x, float)
{
return (x*y);
}
}
class circle implements area //Another implementation
{
Public float compute (float x, float y)
{
return(pi *x*x);
}
}
class interfacetest
{
Public static void main(String args[ ] )
{
Rectangle rect = new rectangle ( );
Circle cir = new circle( );
Area = area;
Area= rect;
System.out.println(“Area of rectangle = “
+ area.compute(10,20));
area = cir;
System.out.println(“Area of Circle = “
+ area.compute(10,0));
}
}

Output: Area of rectangle = 200


Area of circle = 314

Variables in Interface:
II sem BCA JAVA
PROGRAMMING
Variables declared for the interface are interface variables. and all the interface variables
are declared as constants using static and final keywords as follows..
interface Item
{
static final int x= 10;
static final string name = “HDS”;
}
It is also possible to declare interface variables without using the final and static
keywords, because all the variables in an interface are treated as constants.
interface Item
{
int x= 10;
string name = “HDS”;
}
This also allowed.

Exception Handling and


Multithreading Exceptions

Errors in a program:
An error may produce an incorrect output or may terminate the execution of the program
abruptly or even may cause the system to crash.
Errors may be classified into two types..
Compile-time errors: An errors detected by the java compiler due to the wrong usage of
syntax such a errors are called syntax errors. Whenever the compiler displays an error, it
will not create the .class file.
Example: /* This program contains an error */
class error1
{
public static void main(String args[ ] )
{
System.out.println(“Error in the program!”) // missing ;
}
}
Java compiler display an error message
Error1.java : 7 : ‘;’ expected
System.out.println ( Error in the program!”)
1 error
Run-Time Errors: An errors which occurs due to the wrong usage of logic, such errors
are called as run-time errors. Such errors causes termination of execution of the program.
Example:
class error2
{
public static void main(String args[ ] )
{
int a = 10;
int b = 5;
II sem BCA JAVA
PROGRAMMING
int c = 5;
int x = a / (b-c); // Division by zero
System.out.println(“ x = “ + x);
int y = a / (b+c);
System.out.println(“ y = “ + y);
}
}

While executing this program, it displays the following message and stops without
executing further statements
java.lang.ArithmeticException: / by zero
at error2.main(error2.java:10)

Fundamentals of Exception:
Exception:
An Exception is a condition that is caused by a run-time error in the program. when
the java interpreter encounters an error such as dividing an integer by zero, it creates an
exception object an throws it.
If the exception object is not caught and handled properly, the interpreter will display an
error message and terminate the program. If we want the program to continue with the
execution of the remaining code, then we should try to catch the exception object thrown
by the error condition and then display an appropriate message for taking corrective
actions. This task is known as exception handling.
An error handling code that performs the following tasks..
1. Find the problem ( Hit the exception)
2. Inform that an error has occurred ( Throw the exception)
3. Receive the error information (Catch the exception)
4. Take corrective actions (Handle the exception)
An error handling code basically consists of two segments, one to detect errors and to
throw exceptions and the other to catch exceptions and to take appropriate actions.
Built-in-exception
Types of Exceptions:
Some of the common java exceptions are..

Exception Type Cause of Exception


ArithmeticException Caused by math errors such as
division by zero
ArrayIndexOutOfBoundsException Caused by bad array indexes
ArrayStoreException Caused when a program tries to
store the wrong type of data in an
array
FileNotFoundException Caused by an attempt to access a
nonexistent file
IoException Caused by general I/O failures,
such as inability to read from a
file
NullPointerException Caused by referencing a null
object
NumberFormatException Caused when a conversion
between strings and number fails
II sem BCA JAVA
PROGRAMMING
OutOfMemoryException Caused when there’s not enough
memory to allocate a new object
SecurityException Caused when an applet tries to
perform an action not allowed by
the browser’s security strings
StackOveflowException Caused when the system runs out
of stack space.

Exception Handling using try & catch


The basic concepts of exception handling are throwing an exception and catching it.

try Block

Statements that causes Exception object


an exception creator

Throws exception object

catch Block

Statements that handles Exception handler


the exception

Java uses a keyword try to perform a block of code that cause an error condition and
“throw” an exception. A catch a block defined by the keyword catch “catches” the
exception “thrown” by the try block and handles it appropriately. The catch block is added
immediately after the try block.,
………………….
………………….
try
{
Statement; // generates an exception
}
catch (Exception-type e)
{
Statement; // processes the exception
}
……………………
……………………
II sem BCA JAVA
PROGRAMMING
If any one statement in the try block generates an exception, the remaining statements
in the block are skipped and execution jumps to the catch block. Every try statement
should be followed by at least one catch statement.
The catch statement works like a method, it passes a single parameter , which is
reference to the exception object thrown by the try block. If the catch parameter matches
with the type of exception object, then the exception is caught and statements in the catch
block will be executed. Otherwise, the exception is not caught and the default exception
handler will cause the execution to terminate.
Example: program to use of try and catch blocks to handle an arithmetic exception.

class error3
{
public static void main(String args[ ] )
{
int a = 10;
int b = 5;
int c = 5;
int x , y;

try
{
x = a / (b - c); // Exception here
}
catch ( ArithmeticException e )
{
System.out.println(“ Division by zero”);
}
y = a / (b + c);
System.out.println(“ y = “ + y);
}
}

Here, the program did not stop at the point of exceptional condition. It catches the error
condition, prints the error message, and then continues the execution and display the
output as :
Division by Zero
y=1

Multiple Catch Statements


It is possible to put More than one catch statement in the catch block are called multiple
catch statements.
The general syntax for multiple catch statements are as follows..
………………………
………………………
try
{
Statement; // generates an exception
}
catch (Exception-Type-1 e)
{
Statement; // processes exception type 1
II sem BCA JAVA
PROGRAMMING
}
catch (Exception-Type-2 e )
{
Statement; // processes exception type 2
}
.
.
.
Catch (Exception-Type-N e)
{
Statement; // processes exception type N
}
……………………
……………………
When an exception in a try block is generated, the java treats the multiple catch
statements like cases in a switch statement. The first statement whose parameter matches
with the exception object will be executed, and the remaining statements will be skipped.
Program using multiple catch blocks
class error
{
public static void main(String args[ ] )
{
int a [ ] = {5, 10};
int b = 5;
try
{
int x = a[2] / b – a[1];
}
catch (ArithmeticException e)
{
System.out.println(“ Division by zero”);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println(“Array index error”);
}
catch (ArrayStoreException e)
{
System.out.println(“ Wrong data type”);
}
int y = a[1] / a[0];
System.out.println(“ y = “ + y”);
}
}

When, run this program produces the output


Array index error
y =2
II sem BCA JAVA
PROGRAMMING
because, the array element a[2] does not exist. Array a is defined to have only two
elements, a[0], and a[1]. The index 2 is outside the array boundary thus causing the block
catch(ArrayIndexOutOfBoundsException e)

Using finally statement:


Java supports a finally statement that can be used to handle an exception that is not
caught by any of the previous catch statements. finally block can be used to handle any
exception generated within a try block. It may be added immediately after the try block of
after the last catch block as shown below..
try try
{ {
…………. ………….
…………. ………….
} }
finally catch(……)
{ {
…………. ………..
………….. ………..
} }
catch(……)
{
………….
………….
}
.
.
finally
{
…………
…………
}
When a finally block is defined, this is guaranteed to execute, regardless of whether or
not an exception is thrown.

User defined exception


throw keyword:
throwing our own exception:
java allows us to throw our own exceptions, using the keyword throw as follows..
throw new Throwable_subclass;

examples:
throw new ArithmeticException( );
throw new NumberFormatException( );
throwing our own exception:
this uses a user-defined subclass of throwable class. The exception is a subclass of
Throwable and therefore MyException is a subclass of Throwable class.

import java.lang.Exception

class MyException extends Exception


{
II sem BCA JAVA
PROGRAMMING
MyException (String message)
{
super( message);
}
}
class TestMyException
{
public static void main (String args[ ])
{
int x = 5, y = 1000;
try
{
float z = (float) x / (float) y;
if( z < 0.01)
{
throw new MyException (“Number is to small”);
}
}
catch( MyException e)
{
System.out.println(“Caught my exception “);
System.out.println(“e.getmessage( ) );
}
finally
{
System.out.println(“I am always here“);
}
}
}
It produces the following output:
Caught my exception
Number is too small
I am always here
The object e which contains the error message “Number is too small” is caught by the
catch block which then displays the message the getMessage( ) method.
The last line of output is produced by the finally block.

Multithreading:
Thread:
A thread is similar to a program that has a single flow of control . it has a beginning, a
body, and an end, and executes the commands sequentially.
Every java program will have at least one thread is called single-threaded programs . All
the main programs examples are the examples for single-threaded programs, in which
only a single sequential flow of control. i.e. a program begins, runs through a sequence of
executions, and finally ends.
II sem BCA JAVA
PROGRAMMING

class ABC
{
………… Beginning
…………
…………
………… Single-threaded
………… body of execution
…………
………… End
………….
}

Multithreading:
Multithreading is a conceptual programming paradigm where a program(Process) is
divided into two or more subprograms(processes), which can be implemented at the same
time in parallel (i.e. is similar to multitasking - several programs can be executed
simultaneously).
Multithreading is a unique property of java that enables us to use multiple flows of
control in developing programs. Each flow of control may be thought of as a separate tiny
program (or module) known as a thread that runs in parallel to others
A program that contains multiple flows of control is known as multithreaded programs.
Example: consider a java program with four threads, one main and three others. The
main thread is actually the main method module, which is designed to create and start the
other three threads, namely A, B, C.
Once initiated by the main thread, the threads A,B and C run concurrently and share the
resources jointly.
The ability of a language to support multithreads is referred to as concurrency . since
threads in java are subprograms of a main application program and share the same
memory space, they are known as lightweight threads or lightweight processes.
II sem BCA JAVA
PROGRAMMING

Main Thread

………………………
…………………
………………………
………………… Main method
…………………… module
………………
……………………
…………………….

start start start

............... ............... ...............


……….. ……….. ………..
………… ………… …………
…………. …………. ………….
…………. …………. ………….
………… ………… …………
………… ………… …………

Thread A Thread B Thread C

A multithreaded program
Multithreading is helpful in a number of ways
 It enables the programmers to do multiple things at one time. As they can divide
a long program in to threads and executes them in parallel.
 They are extensively used in java-enabled browsers such as hotjava, these
browsers can download a file to the local computer, display a web page in the
window, output another web page to a printer and so on.

Creating a threads:
Threads are implemented in the form of objects that contain a method called run( ). The
run( ) method is the heart of the thread and it is the only method in which the thread’s
behaviour can be implemented. the run( ) method it appears as follows..
II sem BCA JAVA
PROGRAMMING
public void run( )
{
………………
……………… (statements for implementing thread)
……………..
}
The run( ) method should be invoked by an object of the concerned thread.
In java new thread can be created in two ways.
1. Creating a thread using thread class: Define a class that extends Thread class
and override its run( ) method with code required by the thread.
2. Using a Runnable interface: Define a class that implements Runnable
interface. The Runnable interface has only one method, run( ) that is to be
define in the method with the code to be executed by the thread.

Creating a thread using thread class:


Extending the thread class:
We can make our class runnable as a thread by extending the class java.lang.Thread.
it enables us to access all the thread methods directly. It includes the following steps:
1. Declare the class as extending the thread class.
2. Implement the run( ) method that is responsible for executing the sequence of code
that the thread will execute. I
3. Create a thread object and call the start( ) method to initiate the thread execution.

Declaring the Class:


The Thread class can be extended as follows:
class MyThread extends Thread
{
………………….
………………….
…………………….
}

Now we have a new type of thread MyThread.

Implementing the run( ) method:


The run( ) method has been inherited by the class MyThread. We have to override this
method in order to implement the code to be executed by our thread. The basic
implementation of run( )

public void run( )


{
……………
…………… // thread code here
……………
}
When we start the new thread, Java calls the thread's run( ) method, so it is the run( )
where all the actions takes place.
II sem BCA JAVA
PROGRAMMING
Starting New Thread:
To create and run an instance of our thread class, we must write the following:
MyThread aThread = new MyThread( );
aThread.start( ) = / / invokes run( ) method
The first line instantiate a new object of class MyThread.
The second line calls the start( ) method causing the thread to move into the runnable
state.

Example of using the Thread class:


The below program creates three threads A, B, and C for undertaking three different tasks.
The main thread dies at the end of the its main method. before it dies, it creates and starts
all the three threads A, B and C.
The statement
new A ( ) . start ( ); thread A is started . there will be two threads running in the
program thread A. The start( ) method returns back to the main thread immediately after
the run( ) method, thus allowing the main thread to start the thread B.

Creating threads using the thread class


class A extends Thread
{
public void run( )
{
for( int i=l; i<=5; i++)
{
System.out.println("\t From Thread A: i = “ + i );
}
System.out.println("Exit from A");
}
}
class B extends Thread
{
public void run ( )
{
for( int j=l; j<=5; j++)
{
System.out.println("\t From Thread B : j = “ + j );
}
System.out.println("Exit from B ");
}
}

class C extends Thread


{
public void run( )
{
for( int k=l; k<=5; k++)
{
System.out.println("\t From Thread C : k = “ +k );
}
System.out.println("Exit from C ");
II sem BCA JAVA
PROGRAMMING
}
}
class ThreadTest
{
public static void main (String args[ ] )
{
new A( ) .start( );
new B ( ). start ( );
new C( ) .start( );
}
}

Output:
First run
From Thread A: i = 1
From Thread A: i = 2
From Thread B: j = 1
From Thread B: j = 2
From Thread C: k = 1
From Thread C: k = 2
From Thread A: i = 3
From Thread A: i = 4
From Thread B: j = 3
From Thread B: j = 4
From Thread C: k = 3
From Thread C: k = 4
From Thread A: i = 5
Exit from A
From Thread B: j = 5
Exit from B
From Thread C: k = 5
Exit from C

Second run
From Thread A: i = 1
From Thread A: i = 2
From Thread C: k = 1
From Thread C: k = 2
From Thread A: i = 3
From Thread A: i = 4
From Thread B: j = 1
From Thread B: j = 2
From Thread C: k = 3
From Thread C: k =4
From Thread A: i = 5
Exit from A
From Thread B: k = 4
From Thread B: j = 5
From Thread C: k = 5
Exit from C
From Thread B: j = 5
II sem BCA JAVA
PROGRAMMING
Exit from B

Stopping and Blocking a thread:


Stopping a thread:
If we want to stop a thread from running, we call its stop( ) method.
i.e. aThread . stop ( );
This statement causes the thread to move to the dead state.

Blocking a thread:
A thread can also be temporarily suspended or blocked by using either of the following
thread methods:
sleep( ) // blocked for a specified time
suspend( ) // blocked until further orders
wait( ) // blocked until certain condition occurs

2. Implementing a thread using the Runnable interface:


The thread can also be implemented using Runnable interface.
The Runnable interface declares the run( ) method that is required for implementing
threads in the programs. To do this, we must perform the steps:
1. Declare the class as implementing the Runnable interface.
2. Implement the run( ) method.
3. Create a thread by defining an object that is instantiated from this “runnable" class as
the target of the thread.
4. Call the thread's start( ) method to run the thread.

Example: the below Program implementation of the above steps. In main method, we first
create an instance of X and then pass this instance as the initial value of the object threadX
(an object of Thread Class). Whenever, the new thread threadX starts up, its run( ) method
calls the run ( ) method of the target object supplied to it. Here, the target object is
runnable. If the direct reference to the thread threadX is not required, then we may use
statements..
new Thread (new X( )) .start( );

Program to implement Runnable Interface:

class X implements Runnable // Step 1


{
public void run( ) // Step 2
{
for( int i = 1; i<=10; i++)
{
System.out.println("\t ThreadX: " + i );
}
System.out.println ("End of ThreadX");
}
}

class RunnableTest
{
public static void main (String args[ ] )
{
II sem BCA JAVA
PROGRAMMING
X runnable = new X ( ) ;
Thread threadX = new Thread(runnable); // Step 3
threadX. start ( ); // Step 4
System.out.println("End of main Thread");
}
}

Output:
End of main Thread
ThreadX : 1
ThreadX : 2
ThreadX : 3
ThreadX : 4
ThreadX : 5
ThreadX : 6
ThreadX : 7
ThreadX : 8
ThreadX : 9
ThreadX : 10
End of ThreadX

Thread Priority:
In java each thread is assigned a priority, which affects the order in which it is
scheduled for running. The threads of the same priority are given equal treatment by the
Java scheduler and, therefore, they share the processor first-come, first-serve basis.
Java allows us to set the priority of a thread using the setPriority( ) method as follows:

ThreadName . setPriority( intNumber );


The intNumber is an integer value to which the thread's priority is set. The Thread class
defines several priority constants:
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRI ORI TY = 10
The intNumber may assume one of these constants or any value between 1 and 10. the
default setting is NORM_PRIORITY.
Most user-level processes should use NORM_PRIORITY, plus or minus 1.
For a thread of lower priority to gain control, one of the following things should happen:
1. It stops running at the end of run ( ).
2. It is made to sleep using sleep( ).
3. It is told to wait using wait( ).
However, if another thread of a higher priority comes along, the currently running
thread will be preempted by the incoming thread thus forcing the current thread to move to
the runnable state. the highest priority thread always preempts any lower priority threads.

In the below Program the thread A started first, the higher priority thread B has
preempted it and started printing the output first. Immediately, the thread C that has been
assigned priority takes control over the other two threads. The thread A is the last to
complete..
priority in threads:

class A extends Thread


II sem BCA JAVA
PROGRAMMING
{
public void run( )
{
System.out.println(" threadA started " );
for(int i=l; i<=4; i++)
{
System.out.println("\tFrom Thread A : i = “ +i);
}
System.out.println("Exit from A");
}
}
class B extends Thread
{
public void run( )
{
System.out.println("threadB started");
for(int j=l; j<=4; j++)
{
System.out.println("\t From threadB : j = “ + j);
}
System.out.println("Exit from B “);
}
}
class C extends Thread
{
public void run( )
{
System.out.println("threadC started");
for(int k=l; k<=4; k++)
{
System.out.println("\t From threadC : k = “ + k);
}
System.out.println("Exit from C “);
}
}
class ThreadPriority
{
public static void main(String args[ ] )
{
A threadA = new A( );
B threadB = new B( );
C threadC = new C( );
threadC . setPriority( Thread. MAX_PRIORITY);
threadB . setPriority( ThreadA.getPriority( ) +1 );
threadA . setPriority( Thread. MIN_PRIORITY);

System.out.println( “Start thread A”);


threadA.start( );
System.out.println( “Start thread B”);
threadB.start( );
System.out.println( “Start thread C”);
II sem BCA JAVA
PROGRAMMING
threadC.start( );
System.out.println( “End of main thread”);
}
}

Output:
Start thread A
Start thread B
Start thread C
threadB started
From Thread B : j=1
From Thread B : j=2
threadC started
From Thread C : k=1
From Thread C : k=2
From Thread C : k=3
From Thread C : k=4
Exit from C
End of main thread
From Thread B : j=3
From Thread B : j=4
Exit from B
threadA started
From Thread A : i=1
From Thread A : i=2
From Thread A : i=3
From Thread A : i=4
Exit from A

You might also like