java (1)
java (1)
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
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.
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.
BYTE CODE:-
A Java compiler translates/converts Java source code into what known as “Byte Code”. Byte
code is not machine instruction code.
C JAVA
C++ JAVA
Java Environment:-
Java Development kit(JDK)
Tools:-
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:-
Java
compiler
Java Java
enabled web interpreter
browser
II sem BCA JAVA PROGRAMMING
Compiled
Interpreted
Documentation section
Package Statements
Import Statement
Interface Statement
Class Definition
Main method class
{
Body of main method
II sem BCA JAVA PROGRAMMING
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.
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 };
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];
Output: 1 0 0
0 1 0
0 0 1
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(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.
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.
Example:
II sem BCA JAVA PROGRAMMING
Sum =0;
count =1;
while( count<100)
{
sum= sum + count;
count ++;
}
System.out.println(“ Total sum = “ +sum);
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
DEFINING A CLASS:
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.
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;
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.
Example:
class Room
{
int length, breadth;
Room (int x , int y)
{
length = x;
breadth = y;
}
int area( )
{
return(length * breadth);
}
}
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
Types of packages:
Java packages are classified as two types
1) Java API packages
2) user defined packages
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.
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
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
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:
// 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));
}
}
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.
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..
try Block
catch Block
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
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
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
………………
……………………
…………………….
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.
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
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
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( );
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:
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:
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