Sei sulla pagina 1di 23

Module 3 JAVA

Introduction to Java
Java was developed at Sun Microsystems. Work on Java originally began with the goal of
creating a platform-independent language and operating system for consumer electronics.
3.1 Features of the Java Language
The Java language is "a simple, object-oriented, distributed, interpreted, robust, secure,
architecture-neutral, portable, high-performance, multithreaded, and dynamic language.
3.1.1 Simple
Java has simplified C++ programming by both adding features beyond those found in C++ and by
removing some of the features that make C++ a complicated and difficult language to master.
Java is simple because it consists of only three primitive data types-numbers, Boolean types, and
arrays.
Java offers additional simplifications over C++. Operator overloading, is not allowed in Java.
Unlike C and C++, Java has no preprocessor. ​The most important C++ feature left out of Java is
the capability to directly manipulate memory addresses through the use of pointers​.
3.1.2 Object-Oriented
Java is object-oriented. Except for its primitive data types, everything in Java is an object. ​Java's
support for object-orientation does not include multiple inheritance. The designers of the language
felt that the complexity introduced by multiple inheritance was not justified by its benefits.
3.1.3. Distributed
Java facilitates the building of distributed applications by a collection of classes for use in
networked applications. By using Java's URL (Uniform Resource Locator) class, an application
can easily access a remote server. Classes also are provided for establishing socket-level
connections.
3.1.4. Robust
Writing a distributed, multithreaded program that can run on a variety of operating systems with a
variety of processors is not a simple task. To do it successfully, you need all the help your
programming language can offer you. With this in mind, Java was created as a strongly typed
language. Data type issues and problems are resolved at compile-time, and implicit casts of a
variable from one type to another are not allowed.
3.1.5. Secure
Java's robustness is its focus on security. Because Java does not use pointers to directly reference
memory locations, Java has a great deal of control over the code that exists within the Java
environment.
It was anticipated that Java applications would run on the Internet and that they could dynamically
incorporate or execute code found at remote locations on the Internet. Because of this, the
developers of Java hypothesized the existence of a hostile Java compiler that would generate Java
byte codes with the intent of bypassing Java's runtime security. This led to the concept of a
byte-code verifier. The byte-code verifier examines all incoming code to ensure that the code
plays by the rules and is safe to execute. In addition to other properties, the byte code verifier
ensures the following:
● No pointers are forged.
● No illegal object casts are performed.
● There will be no operand stack overflows or underflows.

1
Anil C.B. SNGCE
Module 3 JAVA

● All parameters passed to functions are of the proper types.


● Rules regarding private, protected, and public class membership are followed.
3.1.6. Portable
Java code is portable. It was an important design goal of Java that it be portable so that as new
architectures (due to hardware, operating system, or both) are developed, the Java environment
could be ported to them.
In Java, all primitive types (integers, longs, floats, doubles, and so on) are of defined sizes,
regardless of the machine or operating system on which the program is run. This is in direct
contrast to languages like C and C++ that leave the sizes of primitive types up to the compiler and
developer.
3.1.7 High-Performance
High performance was one of the initial design goals of the Java developers. A Java application
will not achieve the performance of a fully compiled language such as C or C++. For most
applications, including graphics-intensive ones such as are commonly found on the World Wide
Web, the performance of Java is more than adequate.
3.1.8. Multithreaded
Writing a computer program that only does a single thing at a time is an artificial constraint that
we've lived with in most programming languages..
Synchronized threads are extremely useful in creating distributed, network-aware applications.
Such an application may be communicating with a remote server in one thread while interacting
with a user in a different thread.
3.1.9 Dynamic
Because it is interpreted, Java is an extremely dynamic language. At runtime, the Java
environment can extend itself by linking in classes that may be located on remote servers on a
network (for example, the Internet). This is a tremendous advantage over a language like C++ that
links classes in prior to runtime.
In C++, every time member variables or functions are added to a class, it is necessary to
recompile that class and then all additional code that references that class. Of course, the problem
is exacerbated by the fact that you need to remember to recompile the files that reference the
changed class. Using make files reduces the problem, but for large, complex systems, it doesn't
eliminate it.
3.2.CLASS AND ACCESS MODIFIERS

3.2.1 CLASS
● A class is usually described as the template from which the object is actually made.
● A class is nothing but new data type
● Keyword ​class​ is used to create new classes (data types)

Creating a new class:


class className {}
In any given ​.java​ file only one public class and 'n' number of ordinary classes are allowed.
Example: Text Class.java
class MyClass{ }
public class TestClass{ }
Note: ​There are two class in TestClass.java file.

2
Anil C.B. SNGCE
Module 3 JAVA

MyClass, and TestClass.


Creating an instance of a class:
Using ​new​ keyword an instance of a class is created. This is called an object or an instance of that
class.
Example:
public class TestClass {
public static void main (String args[]) {
TestClass TC = new TestClass();
System.out.println("An Instance of a class is created,named as TC");
}
}
Output:
An Instance of a class is created,with a name TC

Methods

● A method in Java is similar to function in C/C++ or any other language


● A method is declared inside a class and belongs to the same class
● A method can be called using . operator as described below

object​.​method()

Method Definition:
The signature of a method is:
return-value-type method-name(parameter-list){ // body }.
Examples:
static void TestMethod1(){ }
public void TestMethod2("Bill") { }
private void TestMethod3("Bill", 55) { }
Example:
public class TestClass {
public void testMethod1(){
System.out.println ("Method.one");
}
public void testMethod2 (String name){
System.out.println (name);
}
public void testMethod3 (int a, String name) {
system.out.println ("My name is "+ name +" and age is " + a);
}
public static void main (String args[]) {
TestClass TC = new TestClass ( );
TC.testMethod1( );
TC.testMethod2("Java programming");
TC.testMethod3 (55, "Bill");
}
}
Output:
Method.one
Java programming
My name is Bill and age is 55

3
Anil C.B. SNGCE
Module 3 JAVA

Member ( Instance ) Variables:


● Accessible from any method in the class.
● Scope of the member variables is the entire class scope.
● If there is no explicit initialization, then the value depends upon the data type of the
member variable.

Example:
public class MyClass {
String s ;
int a ;
long l ;
public void myMethod(){
System.out.println ("default string value is " + s);,
System.out.println ("default int value is " + a);
System.out.println ("default long value is " +l);
}
public static void main (String args[]) {
MyClass mc = new MyClass( );
mc. myMethod( );
}
}
Output:
default string value is null
default int value is 0
default long value is 0

3.2.2. MODIFIERS

Java has access specifiers are public, private, protected. These can be placed infront of each
definition for each member in your class, whether it's a data member or a method. Each access
specifier controls the access for only that particular definition

● public
● private
● protected

The "public" Access Modifier

● Available to everyone, everywhere


● You cannot have more than one public class in a single .java file

3.2.3 The 'private' Access Modifier

● If a member variable is defined as private, available to all methods of the class scope.
● You cannot assign it to top level classes ( except for inner classes).
● A child class cannot access private features of parent class.

Example:
class PrivateClass {
private double d = 10.0;

4
Anil C.B. SNGCE
Module 3 JAVA

private void privateMethod() {


System.out.println(d);
}
}
public class TestClass extends PrivateClass {
public static void main (String args []) {
TestClass t= new TestClass();
t.privateMethod(); // compile time error, private methods are not inherited
PrivateClass pc = new PrivateClass();
pc.privateMethod(); // compile time error, private methods can be called inside class
only
}
}
3.2.4. What is a Package:
● A package is a collection of related classes
● To create a package use ​package​ keyword
● The package statement should be the first line in your .java file only comments are
allowed before package statements
● The package statement should be placed before the import statements

Example:
package pg ;
public class PClass {
public int x ;
public String setX( int i ) {
x=i;
return x;
}
}

Example:
package pg1;
import com.pg.*;
public class PClass1 {
public static void main ( String args [ ]) {
PClass pc= new PClass();
System.out.println("The value of x is " + PC.setX(5));
}
}
Output:
The value of x is 5
3.2.5. The 'protected' Access Modifier
● Protected features are available to all the classes and subclasses within a package.
● Available to only subclasses in a different package.

Example:
package p1;
public class proClass1 {
protected void proTest1() {
System.out.println("protected features are available");

5
Anil C.B. SNGCE
Module 3 JAVA

}
}
package p2;
import p1.*;
public class proClass2 extends proClass1 {
void proTest2() {
proTest1() ;
}
}
Output:
protected features are available
3.2.6. The 'static' Modifier
Static features can be called through class name. So from a static function you cannot access non
static variables and non static functions.
The following example describes the use of static modifier.
Example 1:
public class StaticTest {
static String s= "Hello i am static";
public int x ;
public static void main ( String args[] ) {
System.out.println (s) ;
System.out.println (x); // compile time error, non static features cannot be called
// from static methods or functions
}
}
Output:
StaticTest.java:8: Can't make a static reference to nonstatic variable x in class StaticTest.
System.out.println (x); // compile time error, non static features cannot be called
^
Example 2:
No matter how many instances (objects) of a class exist, only one copy of static variable exists.
Non static features contain it's own copy for each instance.
public class NonStaticTest {
static int x = 10;
public static void main ( String args[] ) {
NonStaticTest nt = new NonStaticTest() ;
nt.x = 20;
NonStaticTest nt1 = new NonStaticTest() ;
nt1.x = 30;
System.out.println (nt.x);
System.out.println (nt1.x);
}
}
Output:
30
30
Note: ​In the above example the variable x is defined as static so objects nt and nt1 shares
common memory location for variable x In the above example if 'x' was defined as non static then
the out-put is 20 followed by 30.
3.2.7. The"final" Modifier

6
Anil C.B. SNGCE
Module 3 JAVA

A final modifier makes the value of a primitive as a constant, with an object reference
variable the reference variable makes it as constant. This means you can't re-assign the same
reference variable to point another object.
A final variable must be initialized at the time of declaration.
If a class is declared as final then all the methods inside the class are implicitly final. So the final
methods may not be overrided. The class cannot be subclassed if defined as final class, this avoids
the inheritance.

Example 1:
class F {
final void fn() { System.out.println ( " I am final " ); }
}
public class TF extends F {
void fn() { System.out.println( "I can't override"); }
}
Output:
TF.java:: The method void fn() declared in class TF cannot override the final method of the same
signature declared in class F. Final methods cannot be overridden.
void fn() {
^
Example 2:
final class F {
void fn() { System.out.println ( " I am final " ); }
}
public class TF extends F {
void fn() { System.out.println( "I can't override"); }
}
Output:
TF.java:: Can't subclass final classes: class F
public class TF extends F {
^
​ inal methods are more efficient than ordinary methods. In the above example 2 class F is
Note:​ F
defined as final, so function fn() is of type final, so we cannot redefine function fn() in derived
class TF. If a class is defined as ‘final’ then all its member variables and functions are of type
‘final’. We cannot derive one class from a ‘final’ class.

3.2.8. The "abstract" Modifier"


An ​abstract class​ is a class that is declared ​abstract​—it may or may not include abstract
methods. In an ordinary class, if one method is declared as abstract,​ t​ hen​ t​ he class must be
declared as abstract.
The abstract class contains only method signatures without body of the method, the body lies in
the subclass. (A subclass must provide the implementation). We can not create object using an
abstract class.
An ​abstract method​ is a method that is declared without an implementation (without braces, and
followed by a semicolon), like this:
abstract void moveTo(double deltaX, double deltaY);
If a class includes abstract methods, the class itself ​must​ be declared ​abstract​, as in:
public abstract class GraphicObject {
// declare fields
// declare non-abstract methods
abstract void draw();
}

7
Anil C.B. SNGCE
Module 3 JAVA

When an abstract class is subclassed, the subclass usually provides implementations for all of the
abstract methods in its parent class. However, if it does not, the subclass must also be declared
abstract
Method Signature:
public abstract void Method() ;
It looks like final and abstract and contradictory, in the sense one cannot be subclassed, and one
must be subclassed.
Example:
abstract class Employee {
abstract void baseSalary();
int i = 100;
}
public class Manager extends Employee {
public void baseSalary() {
i = i * 100; // you must provide implementation. else gives you compile time error
System.out.println( i );
}
public static void main ( String args[] ) {
Manager m = new Manager();
m.baseSalary();
}
}
Output:
10000
3.3. Constructor
In Java constructor is used to initialize the object. The name of the constructor should be
same name as the class name. Constructor does not return any value, and even we cannot use ​void
as a return type.
Calling a default Constructor:
Example 2:
public class Default {
Default() {
System.out.println("Calling Default Constructor.");
}
public static void main(String args[]) {
Default d = new Default(); // Here is the call to default constructor
}
}
Output:
Calling Default Constructor.
3.4. Overloading
In any given class, reusing the same method name with different argument list is known as
method overloading.
Conditions:
● Must have different argument list, or atleast the order of arguments.
● Must have same method name.
● May or may not have same return type. ( free floating return type )

Example:
public class Overload {

8
Anil C.B. SNGCE
Module 3 JAVA

float Method(int x, float f) {


return f;
}
int Method( float f, int x) {
return x;
}
float Method(int x, float f) { // This method declaration is illegal
return x;
}
}
Output:
OverLoad.java:11: Duplicate method declaration: float Method(int, float)
float Method(int x, float f) { // This method declaration is illegal
^
Calling an overloaded methods are like regular method calling.
3.5. Overriding
When you extend a class, all private features are not available to the derived class.
Conditions:
● Must have the same method name.
● Must have same return type.
● Must have same argument list.

Example:
class Shape {
int x, y;
public void setSize(int h, int w) {
this.x = w;
this.y = h;
}
}
public class Rectangle extends Shape {
public void setSize(int h, int w) {
this.x = w;
this.y = h;
}
public static void main(String args[]) {
Rectagle r = new Rectangle();
r.setSize(10, 20);
System.out.println(r.x * r.y);
}
}
Output:
200

3.6. EXCEPTION HANDLING


An Exception is ​an abnormal condition that arises in a code sequence at runtime​. Exception is run
time error such as dividing an integer by zero. Java allows Exception handling mechanism to
handle various exceptional conditions. When an exceptional condition occurs, an ​exception is
thrown. If the Java virtual machine or run-time environment detects a semantic violation, the
virtual machine or run-time environment implicitly throws an exception

9
Anil C.B. SNGCE
Module 3 JAVA

3.6..1 Handling Exceptions


Java provides the Exception handling mechanism with the help of the three statements
Three statements are:
● The ​try statement identifies a block of statements ​within which an exception might be
thrown.
● The ​catch statement must be associated with a try statement and ​identifies a block of
statements that can handle a particular type of exception. ​The statements are executed if an
exception of a particular type occurs within the try block.
● The ​finally statement must be associated with a try statement and identifies a block of
statements that ​are executed regardless of whether or not an error occurs within the try
block​.
Here's the general form of these statements:
try {
​statement(s)
} catch (​exceptiontype​ ​name)​ {
statement(s)
} finally {
statement(s)
}

Here is an example of a try statement that includes a catch clause and a finally clause:
try {
d=0;
a=42/d;
}
catch (ArithmeticException e) {
System.out.println("Division by Zero");
}
If a=42/d throws an ArithmeticException, the exception is caught by the catch clause.
When the java interpreter encounters an error such as divide by zero, it creates an exception object
and throws it ( ie it informs that an error has occurred.) If the exception object is not caught and
handled properly, the interpreter will display an error message and will terminate the program.

10
Anil C.B. SNGCE
Module 3 JAVA

3.6.2. Common Java Exceptions


ArithmeticException – caused by math errors such as division by zero
ArrayIndexOutOfBoundsException caused by bad array indexes
FileNotFoundException Caused by an attempt to access a nonexistent file

IOException caused by general I/O failures


InterruptedException – one thread has been interrupted by another thread.

3.6.3 Throws
When a method handles an exception it must be specified that this method throws an exception.
This is done using throws clause.
Syntax
Returntype ​methodname(parameters)​ throws exception
If a method is expected to throw any exceptions, the method declaration must declare that in a
throws clause. If a method implementation contains a throw statement, it is possible that an
exception will be thrown from within the method. In addition, if a method calls another method
declared with a throws clause, there is the possibility that an exception will be thrown from within
the method. If the exception is not caught inside the method with a try statement, it will be thrown
out of the method to its caller. Any exception that can be thrown out of a method in this way must
be listed in a throws clause in the method declaration. The classes listed in a throws clause must
be Throwable or any of its subclasses; the Throwable class is the superclass of all objects that can
be thrown in Java.

3.6.4 Finally Clause


Finally clause will execute whether or not an exception is thrown in the corresponding
try block. Finally clause will execute if try block exits. The finally clause is optional. If it is
present, it is placed after the last catch clause. If an exception is thrown, the finally block will
execute even if no catch statement match the exception. Any time a method is about to return to
the caller from inside try/catch block, via an uncaught exception or an explicit return statement,
the finally clause is also execute.

public class a{

11
Anil C.B. SNGCE
Module 3 JAVA

public static void main(String args[])


{int d,a;
try {
d=0;
a=42/d;
}
catch (ArithmeticException e) { System.out.println("Division by Zero"); }
finally{ System.out.println("Division by Zero1");}
System.out.println("Division by Zero2");
}
}
Output
Division by Zero
Division by Zero1
Division by Zero2
INTERFACES
Using ​interface​, we can specify what a class must do, but not how it does it. Interfaces are
syntactically similar to classes, but they lack instance variables, and their methods are declared
without any body.
Once it is defined, any number of classes can implement an ​interface​. Also, one class can
implement any number of interfaces. To implement an interface, a class must create the complete
set of methods defined by the interface. However, each class is free to determine the details of its
own implementation.
Defining an Interface
An interface is defined much like a class. This is the general form of an interface:
access i​ nterface ​name {​
return-type method-name1(​ ​parameter-list)​ ​;
return-type method-name2(​ ​parameter-list)​ ​;
return-type method-nameN(​ ​parameter-list)​ ​;
}

Here, ​access ​is either ​public ​or not used. When it is declared as ​public​, the interface can be used
by any other code. ‘​name’ i​ s the name of the interface, and can be any valid identifier. Notice that
the methods, which are declared have no bodies. They end with a semicolon after the parameter
list.
Variables can be declared inside of interface declarations. They are implicitly ​final ​and
static.​ The implementing class cannot change variables.
Here is an example of an interface definition. It declares a simple interface which contains
one method called ​call( ) ​that takes a single integer parameter.

interface Callback {
void call(int param);
}
Implementing Interfaces
Once an ​interface ​has been defined, one or more classes can implement that interface. To
implement an interface​, include the ​implements ​clause in a class definition, and then create the
methods defined by the interface. The general form of a class that includes the ​implements ​clause
looks like this:
access c​ lass ​classname i​ mplements ​interface1,​,​interface2...
12
Anil C.B. SNGCE
Module 3 JAVA

{
// class-body
}
Here is a small example class that implements the ​Callback ​interface shown earlier.

class Client implements Callback {


public void call(int p) {
System.out.println("callback called with " + p);
}
}
It is both permissible and common for classes that implement interfaces to define additional
members of their own. For example, the following version of ​Client ​implements ​call( ) ​and adds
the method ​nonIfaceMeth( )​:
class Client implements Callback {
// Implement Callback's interface
public void call(int p) {
System.out.println("callback called with " + p);
}
void nonIfaceMeth() {
System.out.println("Classes that implement interfaces may also define other members, too.");
}
}

NESTED AND ANONYMOUS INNER CLASSES

NESTED CLASSES

A class used to serve other class can be implemented through nested classes. ​A nested class is a
class defined within the scope of another class.

Consider the following example:


public class Outer {
private int A=3;
public class Nested {
public void DisplayA() {
Outer o= new Outer();
System.out.println(o.A);
}
}
}
As it shows, it is entirely possible for the member of a class to be another user-defined type. If
you read the above code snippet closely, you can see that the nested class' method DisplayA is
trying to access the outer class private variable A. ​Nested classes have the advantage of access to
all the members of the outer class​.

The nested class in the example has a public access modifier and it can be instantiated within the
scope of the outer class. For example:

13
Anil C.B. SNGCE
Module 3 JAVA

Outer.Nested n1 = new Outer.Nested();


Of course nested classes can have private access, in this case ​only the outer class methods can
have access to the nested class.

Below is the full example:


public class Outer {
private int A;
public Outer(int a) {
A = a;
}
public class Nested {
public void DisplayA(Outer o) {
System.out.println (o.A);
}
}
}
public class Tester {
static void Main() {
Outer o1 = new Outer(4);
Outer.Nested n1 = new Outer.Nested();
n1.DisplayA(o1);
}
}

ANONYMOUS INNER CLASSES - A VERY BRIEF INTRODUCTION

Anonymous inner classes are local inner classes that don't have a class name. The keyword class
is missing, and there are no modifiers (public, protected, and so on).
Anonymous inner classes cannot be public, protected, private, or static. The syntax for
anonymous inner classes does not allow for any modifiers to be used. The keywords extends and
implements are missing too. These keywords aren't allowed because we create anonymous inner
classes through another extension to the new operator syntax.
They must always (implicitly) extend a superclass or implement some interface even though you
never use the extends or implements keywords​.
Right after the new someClass () syntax, a curly brace is used to start a class definition. ​There is
no constructors for an anonymous inner class because they don’t have name​. An instance
initializer is a block of code (not a method!) that automatically runs every time a new instance of
an object. In effect, it is an anonymous constructor! Anonymous inner classes have access to final
local variables and method arguments.
The Java compiler writes multiple anonymous inner classes in an enclosing class into sequentially
numbered class files prefixed with the name of the enclosing class and a dollar sign.
When an anonymous inner classes inside other inner classes is created, their numeric postfix is
appended to the outermost enclosing class, not the inner class in which they are defined. you'll see
Outer$1.class even if the anonymous inner class is defined in the Outer.Inner class.
An anonymous class is implicitly final. An inner class has full access rights to its enclosing class.
Local and anonymous inner classes can still access all the instance variables and methods of the
enclosing class.

14
Anil C.B. SNGCE
Module 3 JAVA

Local and anonymous inner classes can access only those local variables and method arguments
that are declared final. This means that you cannot change the value of local variables from within
the code of the inner class. They are read-only.
Example,
public class Foo {
int a = 10;
int c = 30;
public Runnable getRunnable () {
int a = 20; // Not OK
return new Thread () {
public void run () {
// Compile time error:
// Cannot refer to a non-final variable inside an inner class defined in a different method
int b = a + c; // Not OK

}
};
}
}
Note: A semicolon is needed at the end of the declaration of an anonymous class.
MultiThreaded Programming

Multithreading is a conceptual programming paradigm where a program is divided into


subprograms which can be implemented in parallel. A thread is a single sequential flow of control
within a program. During the runtime of the thread, there is a single point of execution. A thread
itself is not a program; it cannot run on its own. It runs within a program.

A Multithreaded programs contains two or more parts that can run concurrently. Each part is
known as thread and each thread defines different flow of execution.

In reality, the single processor is executing one thing at a time and switches between the processes
so fast that it appears to human beings that all of them are being done simultaneously. Java
Interpreter handles the switching between the processes.
Creating 2 threads
Program
class NewThread implements Runnable {

15
Anil C.B. SNGCE
Module 3 JAVA

public void run() {


try {
for(int i = 0; i <20 ; i=i+2) {
System.out.println("Even Thread: " + i);
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
}
}

class NewThread2 implements Runnable {


public void run() {
try {
for(int i = 1; i <20; i=i+2) {
System.out.println("Odd Thread: " + i);
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Child2 interrupted.");
}
}
}

class ThreadDemo {
public static void main(String args[]) {
NewThread t=new NewThread(); // create a new thread
NewThread2 t2=new NewThread2(); // create a new thread
try {
Thread tt= new Thread(t);
Thread tt2= new Thread(t2);
tt.start();
tt2.start();
}
catch (Exception e) {
System.out.println("Main thread interrupted.");
}
}
}
Testing
E:\JAVA_LAB\T03>java ThreadDemo
Even Thread: 0
Odd Thread: 1
Even Thread: 2
Odd Thread: 3
Even Thread: 4
Odd Thread: 5
Even Thread: 6
Odd Thread: 7
Even Thread: 8
Odd Thread: 9
Even Thread: 10
Odd Thread: 11

16
Anil C.B. SNGCE
Module 3 JAVA

Even Thread: 12
Odd Thread: 13
Even Thread: 14
Odd Thread: 15
Even Thread: 16
Odd Thread: 17
Even Thread: 18
Odd Thread: 19

THE LIFE CYCLE OF A THREAD


The main stages in the life-time of a thread are shown in the following figure:

When a thread (object) is first created,it is in the ​New Thread​ state. It remains in this state until
the thread is actually ​started​. The thread is started using the method start(). Now it moves to the
Runnable state. The Runnable state indicates that it is ready for execution and is waiting for the
availability of processor. If the processor has given its time to the thread, it moves to Running
state. The thread runs until it is preempted by a higher priority thread or it finishes its execution or
it is interrupted.
The thread goes to Not Runnable state if the thread is suspended, sleeping or waiting in order to
satisfy certain requirements.

Suspend()​ method is used to suspend the execution of a thread for some time. And the suspended
thread can be resumed by using the method resume()

Sleep(t)​ method is used to make the thread sleep for a specified time in millisecs. The thread
re-enters the runnable state after the specified time ​t

Wait() method is used make the thread wait unitl some event occurs. The notify() method is used
to run the thread again.

17
Anil C.B. SNGCE
Module 3 JAVA

Dead State
A running thread ends its life when it has completed its execution.
CREATING THREADS

When a java program starts, the main thread begins running immediately. It is the thread from
which other threads are created and it must be the last thread to finish the execution. When the
main thread stops execution, the program terminates.

A new thread is created as an instance of the java.lang.Thread class. To create a thread, a new
instance of this class must be created. The thread is started with the method Thread.start(). When
this method is called, the thread begins executing in the run() method of the target class. A new
Thread class always starts running the public void run() method of a class. There are two ways to
create a thread:
● Extend the Thread class. With this technique the new class inherits from the class Thread.
The thread can start running in the class's run method.
● By converting a class to a thread : Define a class that implements the runnable interface.
The runnable interface has only one mother, run().
Extending the Thread Class
When creating a new thread by extending the Thread class, you should override the run() method.
public class MyThread extends Thread
{ public void run()
{ // do something
}
}

To start a new thread, use the inherited method ​start()


MyThread ft = new MyThread();
ft.start();
A thread can also be created by implementing the Runnable interface instead of extending the
Thread class.
public class MyThread implements Runnable
{ public void run()
{ // do something
}
}

18
Anil C.B. SNGCE
Module 3 JAVA

Creating Multiple Threads


Example 1
class NewThread implements Runnable
{ public void run()
{ for(int i=5;i>0;i--)
System.out.println("first thread : "+ i);
}
}
class NewThread2 implements Runnable
{ public void run()
{ for(int i=5;i>0;i--)
System.out.println("Second Thread : "+ i);
}
}
class MultiThreadDemo
{
public static void main(String args[])
{
NewThread Ob1 = new NewThread();
NewThread2 Ob2 = new NewThread2();
Thread t1=new Thread (Ob1)
Thread t2 =new Thread (Ob2)
T1.start();
T2.start();

Output
first thread : ​5
Second Thread : ​ 5
first thread : ​4
Second Thread : ​ 4
first thread : ​3
Second Thread : ​ 3
first thread : ​2
Second Thread : ​ 2
first thread : ​1
Second Thread : ​ 1

Starting a Runnable
Pass an object that implements Runnable to the constructor of a Thread object, then start the
thread as before.
MyThread fr = new MyThread();
new Thread(fr).start()

19
Anil C.B. SNGCE
Module 3 JAVA

Thread Synchronization
Multiple threads of execution can manipulate a shared object or variable. When multiple threads
share an object and that object is modified by one or more of the threads, indeterminate results
may occur unless the shared object is managed properly. The problem can be solved by giving
one thread at a time exclusive access to code that manipulates the shared object. During those
time, other threads desiring to manipulate the object should be kept waiting. When the thread with
the exclusive access to the object finishes manipulating the object, one of the threads that was
kept waiting should be allowed to proceed. Each thread accessing the shared object excludes all
other threads from doing so is called ​Thread Synchronization​.
Java uses monitor to perform synchronization. A monitor is an object that is used as a mutually
exclusive lock. To coordinate shared data access among multiple threads, the JVM associates a
lock with each object and class. A lock is like a privilege that only one thread can possess at any
one time. If a thread wants to lock a particular object or class, it asks the JVM, the JVM gives the
lock to the thread. When the thread no longer needs the lock it returns it to the JVM. That is only
one thread can own a monitor at a given time. When a thread enters a monitor (or acquires a lock)
all the other threads attempting to enter the monitor will be suspended until the first thread exits
the monitor.

The form of monitor used by JVM is called a “Wait and Notify” monitor, also called as Signal
and Continue monitor. In this kind of monitor, a thread that currently owns the monitor can
suspend itself inside the monitor by executing a wait command. When a thread executes a wait, it
releases the monitor and enter a wait set. The thread will stay suspended in the wait set until some
time after another thread executes a notify command inside the monitor. When a thread executes
notify, it continues to own the monitor. After the notifying thread has released the monitor, the
waiting thread will reacquire the monitor.

EVENT HANDLING (EVENT DELEGATION MODEL)

GUI applications are event-driven. They generate some events when the user of the
program interacts with the GUI. Clicking a button, closing a window, or hitting a key, results in
an appropriate event being sent to the application.
In Java, events are represented by objects. When an event occurs, the system collects all
the information relevant to the event and constructs an object to contain that information​.
Different types of events are represented by objects belonging to different classes. For example,
when the user presses a button on the mouse, an object belonging to a class called M​ ouseEvent is
constructed. The object contains information such as the GUI component on which the user
clicked, the (​ x,y) coordinates of the point in the component where the click occurred, and which
button on the mouse was pressed.
For an event to have any effect, a program must detect the event and react to it. In order to
detect an event, the program must "listen" for it. Listening for events is something that is done by
an object called an ​event listener​. An event listener object must contain a function for handling
the events for which it listens. For example, if an object is to serve as a listener for events of type
MouseEvent​, then it must contain the following method (among several others):
public void mousePressed(MouseEvent evt) { . . . }
The body of the method defines how the object responds when it is notified that a mouse button
has been pressed. The parameter, ​evt​, contains information about the event. This information can
be used by the listener object to determine its response. The methods that are required in a mouse

20
Anil C.B. SNGCE
Module 3 JAVA

event listener are specified in an ​interface named ​MouseListener​. To be used as a listener for
mouse events, an object must implement this ​MouseListener​ interface

ie .,The event handling in Java based on event delegation model. Its principal elements are
o Event Objects
Encapsulates information about different types of user interaction
o Event source objects
Particular GUI Component with which the user interacts. They inform event listeners
about events when these events occur and supply the necessary information about these
events
o Event Listener
Is an object that is notified by the event source when an event occurred. It then responds
to the event.

GUI event information is stored in an object of a class that extends AWTEvent. AWTEvent class
is further divided into two groups

1. Semantic Event – events to represent user interaction with GUI component


o ActionEvent
This event is generated by an action performed on a GUI component. The GUI
components that generate this event are:
▪ Button – when a button is clicked
▪ List – when a list item is double clicked
▪ MenuItem – when a menu item is selected
▪ TextField- when the ENTER key is hit in the text field.
String getActionCommand() returns the name associated with this action. The
command name is a button name, list-item name, an menu-item name or text.
o AdjustmentEvent
o ItemEvent
This event is generated when an item is selected or deselected in an ItemSelectable
component.
GUI component that generate this event are:
▪ Checkbox – when the state of the check box changes
▪ CheckboxMenuItem- when the state of the check box associated with the
menu-item changes.
▪ Choice- when an item is selected or deselected from a choice-list
▪ List - when an item is selected or deselected from a list
Object getItem() returns the object that was selected or deselected.
Int getStateChange() returns the value indicates whether it was selected or
deselected.
o TextEvent
2. Low-Level Events
o ComponentEvent
o KeyEvent
o MouseEvent
o WindowEvent
(Not necessary to study everything on the above list, It is not important)
A Programmer must perform two key tasks to process a graphical user interface event in a
program.
o Register an event listener for the GUI component that is expected to generate the event
o Implement a event handling method.

21
Anil C.B. SNGCE
Module 3 JAVA

When an event occurs, the GUI component with which the user interacted notifies its registered
listeners by calling each listeners appropriate event-handling methods.

Listeners for different Events


For each event type that can occur, the application can add event listeners, which have methods
invoked when the event occurs. The listeners are defined as interfaces so that the actual listener
has to implement these methods.
(not necessary to study everything on the table given below. It is not important)

Event Listener Method


ActionEvent ActionListener ActionPerformed()
AdjustmentEvent AdjustmentListener AdjustemntValueChanged()
ComponentEvent ComponentListener ComponentResized()
componentMoved()
componentShown()
componentHidden()
FocusEvent FocusListener focusGained()
focusLost()
ItemEvent ItemListener itemStateChanged()
WindowEvent WindowListener windowClosed()
windowClosing()

Example 1
Handling Buttons
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class ButtonApplet extends java.applet.Applet implements ActionListener {
Button button;
String msg;
public void init() {
button= new Button("click here");
add(button);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
String str= e.getActionCommand();
if(str.equals("click here"))
msg="Welcome to Event Handling";
}
public void paint(Graphics g) {
g.drawString(msg, 10,100);
}
}

Example 2
Handling CheckBox

import java.awt.*;
import java.applet.*;
import java.awt.event.*;

22
Anil C.B. SNGCE
Module 3 JAVA

public class CheckboxApplet extends java.applet.Applet implements ItemListener{


String msg;
Checkbox option1;
Checkbox option3;
public void init() {
option1 = new Checkbox("Large Pizza");
option3 = new Checkbox("Small Pizza");
option1.setState(true);
add(option1);
add(option3);
option1.addItemListener(this);
option3.addItemListener(this);
}
public void itemStateChanged(ItemEvent e)
{
repaint();
}
public void paint(Graphics g)
{
msg="Current State:";
g.drawString(msg,6,80);
msg="Large Pizza " + option1.getState();
g.drawString(msg,6,100);
msg="Small Pizza " + option3.getState();
g.drawString(msg,6,140);
}
}

23
Anil C.B. SNGCE

Potrebbero piacerti anche