Вы находитесь на странице: 1из 265

| 

What is java?

‡ Developed by Sun Microsystems (James Gosling)

‡ A general-purpose object-oriented language

‡ Based on C/C++

‡ Designed for easy Web/Internet applications

‡ Widespread acceptance
Java Features (1)
‡ Simple
± fixes some clumsy features of C++
± no pointers
± automatic garbage collection
± rich pre-defined class library http://java.sun.com/j2se/1.4.2/docs/api/
‡ Object oriented
± focus on the data (objects) and methods manipulating the data
± all functions are associated with objects
± almost all datatypes are objects (files, strings, etc.)
± potentially better code organization and reuse
Java Features (2)
‡ Änterpreted
± java compiler generate byte-codes, not native machine code
± the compiled byte-codes are platform-independent
± java bytecodes are translated on the fly to machine readable
instructions in runtime (Java Virtual Machine)

‡ Portable
± same application runs on all platforms
± the sizes of the primitive data types are always the same
± the libraries define portable interfaces
Java Features (3)
‡ eliable
± extensive compile-time and runtime error checking
± no pointers but real arrays. Memory corruptions or unauthorized
memory accesses are impossible
± automatic garbage collection tracks objects usage over time

‡ Secure
± usage in networked environments requires more security
± memory allocation model is a major defense
± access restrictions are forced (private, public)
Java Features (4)
‡ jultithreaded
± multiple concurrent threads of executions can run simultaneously
± utilizes a sophisticated set of synchronization primitives (based
on monitors and condition variables paradigm) to achieve this

‡ Dynamic
± java is designed to adapt to evolving environment
± libraries can freely add new methods and instance variables
without any effect on their clients
± interfaces promote flexibility and reusability in code by specifying
a set of methods an object can perform, but leaves open how
these methods should be implemented
± can check the class type in runtime
Java Disadvantages

‡ Slower than compiled language such as C


± an experiment in 1999 showed that Java was 3 or 4 times slower
than C or C++
› ››› 
       ›
›› ›
± adequate for all but the most time-intensive programs
Getting Started: (1)
r  Create the source file:
± open a text editor, type in the code which defines a class
(A!"#) and then save it in a file (A!"#$)
± file and class name are case sensitive and must be matched
exactly (except the V  part)
Example Code: HelloWorldApp.java

 





 

 


   



 




   ! "
#
 



V V 
 


"$
%
%
U |&''())*'
Getting Started: (2)
r Compile the program:
± compile HelloWorldApp.java by using the following command:

 


V 

it generates a file named HelloWorldApp.class


Uš 
   
 

      
 
   
 
if you see one of these errors, you have two choices:
1) specify the full path in which the  program locates every time.
For example:
&+, -./V0V-123,,  


V 

2) set the PATH environment variable


Getting Started: (3)

r un the program:


± run the code through:
 



± Note that the command is , not , and you refer to



, not 


V  or



V


U ü 
 
      ü 
 ! "
if you see this error, you may need to set the environment variable
CLASSPATH.
Language basics (1)
‡ Data types
± 8 primitive types:
‡ boolean, byte, short, int, long, float, double, char
± Class types, either provided by Java, or made by programmers
‡ String, Integer, Array, Frame, Object, Person, Animal, «
± Array types
‡ Variables
± "›% "›  &'( )

± Example variable declarations and initializations:


int x; x=5; int[] intArray;
boolean b = true; intArray = new int[2];
Frame win = new Frame(); intArray[0] = 12;
String x = ³how are you?´; intArray[1] = 6;
Person pArray = new Person[10];
Java Data Types

‡ Java has two kinds of types:


± h 
   or  

±   or 
 
‡ No variable can be used until it is
defined.
‡ Java is a strongly typed language.
Java Primitive Data Types
]ri itiv T t r U R

t - it i te er t 7

rt - it i te er ,7 t ,7 7

i t - it i te er ±2,147,483,648 t 2,147,483,647

l - it i te er t

fl t - it fl ati -p i t 6 i ifi t i it , r10 ±46 , 10 38 

l - it fl ati -p i t 15 i ifi t i it , r10 ±324 , 10 308 


r U ic e c aracter

l lea varia le false a tr e


Data Types, Default Values
Primiti e ype Default Value ‡ No variable can have
byte 0 an undefined value.
short 0 ± Instance or class variables
int are implicitly initialized to a
long 0 standard default value.
float + . f ± Local ariables are not
double + . d implicitly initialized to a
char \u0000 default value and must be
boolean false
explicitly initialized.
"obj-ref" null
Rules for naming an identifier
‡ An identifier can be up to 255 characters
long.
‡ It must start with a letter, an underscore, or a
dollar sign.
‡ se letters, dollar signs, underscores, or
digits for subsequent characters.
‡ It is generally better if you stick to letters,
digits, and underscore characters.
‡ Java is a case-sensitive language
‡ Do not use Java keywords
palid Identifier Names
à
Ä  

   

   

  Ä 

 
   


 Ä  !

  !  !
"  #$ %
 # % % !
 ! &'( !
% !à
|ava Keywords
i  
 
 

 

 
 
  
i
 i   

 


  
   
   
  
 

  
 
 
 i   


 
  
  

   
    
i




 

    
 

  i  
  

Naming Guidelines
‡ Start variable names with a lowercase
letter.
‡ Capitalize the first letter of all words after
the first word. (I.E. salesTaxAmount )
‡ Capitalize all letters in constants.
‡ Try to use meaningful names that are easy
to remember when coding.
Yrithmetic operators
Operator Name Description
þ    

     
 
   

 

     
 
 
  

 

  
 
 
  

 

  
  
 
   
 



 
  

 

þþ 

   

 !" # " þ $
 


     

 !" # "  $
þ %
 % 
 &
'  '   &
  

&

 (
 
 ) 
 
 
 
 
'  



Precedence of Arithmetic operators
± erator(s) ± eratio (s) ±r er of eval atio ( rece e ce)

() Pare t eses Eval ate first. If t e are t eses are


este , t e ex ressio i t e i ermost
air is eval ate first. If t ere are
several airs of are t eses o t e
same level (i.e., ot este ), t ey are
eval ate left to rig t.
*, / a % M lti licatio Eval ate seco . If t ere are several
Divisio of t is ty e of o erator, t ey are
Mo l s eval ate from left to rig t.
+ or - A itio Eval ate last. If t ere are several of
S btractio t is ty e of o erator, t ey are eval ate
from left to rig t.
Mathematical Functions
‡ Java provides a range of methods that support
such functions as part of the standard library in
the package  , all these are available in
your program automatically.
‡ The methods that support various additional math
functions are implemented in the class 
‡ To reference a particular function you need to
write *› and a period in front of the function
name. To use +› , which calculates the square
root of whatever you place between the
parentheses, you would write:
   
‡ Sun Documentation: Math class
±ther assignment operators

4 
  
à
±   
      
þ  þ   þ  
       
  
   
  

  
   
   
       
à
Integer Variables

Declaring and Initializing:


int myNumber = 12345;
byte luckyNumber = ;
short smallNumber = 1234;
long bigOne = 999999999L;
long big = 999999999L, largeNum = 100000000L;
long xCoord=0L, yCoord=0L;
Decimal Constants
‡ A decimal constant must not begin with a
0. An octal constant begins with a 0 and a
hexadecimal constant begins with 0x or
0X.
‡ The 
 package has a
# $
class for arbitrary-precision
integer arithmetic.
Floating-point types
‡ The floating-point types are  
(32
bits) and   (64 bits).
‡ A floating-point constant such as %&' is
of type   , whereas %&' and
%&' are of type  
.
Floating point Variables
As with integer calculations, floating point
calculations in Java will produce the same
results on any computer. Declaring and
Initializing:
‡ double sunDistance = 1.496E8;
‡ float hisWeight = 185.2F;
boolean Variables
‡ Recall that boolean expressions evaluate either
  of 4
.
‡ You can use 
 variables to store the
result of evaluating a boolean expression
boolean midDay =(hour == 12);
‡ nlike C++ you can not assign a numeric value
to boolean data, although you can use the
values of true & false.
boolean flag = false;
Data type char

u  variables can store any character in the


—nicode character set
Ò This includes any keyboard character in addition
to many others.
‡ You must enclose  values in single
quotes
Ò E.g. š56š/56š 5
Ò E.g.  
 7š5$
‡ Some special nicode characters are known
as escape sequences
Ò E.g. š,5is the new-line character
üscape sequences

M   ri ti M   ri ti
È l

È 4 


È *  ÈÈ  + 
È 
  ȝ X   +
üscape sequences e amples

Code esulting string


& +8 ,9 +:/0V3; & +8 
 9 +:/0V3;
| ,, <,=8,  | 
 <=8
#  >+,, ,, #  >+, ,
,?, ? ? ?

tring o jects

T t t ti j t
i t O k
String title = new String("War and Peace");
— i t t
String title = "War and Peace";

E l tt t ti jt


String title = "Moby Dick";
String book = title;
String code = "";
String inputValue = null;
Relational operators
‡ Standard relational operators for comparing
values, return in true or false:
> greater than
less than
> greater than or equal to
 less than or equal to
 equals
 and not equals
‡ The equality operator should be used with
caution on floating-point values and object
references.
Equality & Relational Operators
Standard algebraic Java equality Example Meaning of
equality or relational or relational of Java Java condition
operator operator condition
ü 
    
;  (  is equal to (

 (  is not equal to (

R
 
    


> >(  is greater than (

à
  (  is less than (

> >(  is greater than or equal to (

?   (  is less than or equal to (


Logical Operators
‡ Java has the standard logical operators:
 and
inclusive-or
 not
‡ Evaluation of a logical-and expression
terminates with a value of  at the first
 subexpression.
‡ Evaluation of a logical-or expression terminates
with a value of
 at the first

subexpression.
Logical Operators
‡ Logical expressions evaluate left to right.
‡ The bit operators  and behave as
logical operators if their operands are
  s instead of integers.
The Logical Operators

ym ol Long name

‡ There are five in Java.   (



Because they
compare or combine 
  (

boolean expressions,
  ,
8
they are also called
Boolean Operators. 88  ,

‡ Operator results are   


 
!(,*$
Boolean.
Logical ±perators

Operator Name Description


  
   
 


"


 

, 
   
 




"
   

 ( 


 
 



"

op= Operators

þshortcut addition, gi en X=
X þ)*¢¢   
ï shortcut subtraction, gi en X=
X -+*¢¢  
o 



 ,'
,oï %*¢¢  

- 

 ,'
,-+*¢¢  
 4 operator
‡ This operator tests whether an object
instantiates a class. Illustrated by this
code segment

 .
/0*
/
 1 
0--

 /
 
0--


Program Comments

‡ Java supports 3 ways of including comments:


line comments, block comments and
documentation comments.
± ¢¢ line comment, rest of line ignored by compiler
± ¢ .. ¢ block comments, all text between /* and */
ignored by compiler.
± ¢
This is a documentation comment.
¢
Program Comments
‡ Documentation Comments
¢
his is a documentation comment.
¢
± Any asterisks at the beginning of each line in a
documentation comment are ignored, as are any
spaces
preceding the first *.
± A documentation comment can also include HTML
tags, as well as special tags beginning with @ that
are used to document methods and classes in a
standard form. The @ is followed by a keyword that
defines the purpose of the tag.
Classes and Objects in Java

Basics of Classes in Java


Contents
‡ Introduce to classes and objects in Java.

‡ nderstand how some of the OO concepts


learnt so far are supported in Java.

‡ nderstand important features in Java


classes.
Introduction
‡ Java is a true OO language and therefore the underlying
structure of all Java programs is classes.
‡ Anything we wish to represent in Java must be
encapsulated in a class that defines the ³state´ and
³behaviour´ of the basic program components known as
objects.
‡ Classes create objects and objects use methods to
communicate between them. They provide a convenient
method for packaging a group of logically related data
items and functions that work on them.
‡ A class essentially serves as a template for an object
and behaves like a basic data type ³int´. It is therefore
important to understand how the fields and methods are
defined in a class and how they are used to build a Java
program that incorporates the basic OO concepts such
as encapsulation, inheritance, and polymorphism.
Classes
‡ A  is a collection of  " (data) and
›" (procedure or function) that
operate on that data.

Circle

centre
radius
circumference()
area()
Classes
‡ A  is a collection of  " (data) and ›"
(procedure or function) that operate on that data.
‡ The basic syntax for a class definition:
class ,  [extends
- , ]
{
[fields declaration]
[methods declaration]
‡ Bare bone class
} ± no fields, no methods

   ) 
-
 &  
 
.
Adding Fields: Class Circle with
fields
‡ Add  "
   ) 
-
 
"' &/  

  

 
/    
 

‡ The fields (data) are also called the


› varaibles.
Adding Methods
‡ A class with only data fields has no life. Objects
created by such a class cannot respond to any
messages.
‡ Methods are declared inside the body of the
class but immediately after the declaration of
data fields.
‡ The general form of a method declaration is:

type MethodName (parameter-list)


{
Method-body;
}
Adding Methods to Class Circle
   ) 
-

 
"' &/  

 
 

 
/     


 
   




 
 


!$ -

  01 2 /
.
 

!$ -

  1 2   / Method Body
.
.
Data Abstraction
‡ Declare the Circle class, have created a
new data type ± Data Abstraction

‡ Can define variables (objects) of that type:

) 
) 
/
) 
) 
/
Class of Circle cont.
‡ aCircle, bCircle simply refers to a Circle
object, not an object itself.

) 
) 

null null

Points to nothing (Null Reference) Points to nothing (Null Reference)


Creating objects of a class
‡ Objects are created dynamically using the
. keyword.
‡ aCircle and bCircle refer to Circle objects
) 
# 
 ) 
!$ ; ) 
# 
 ) 
!$ ;
Creating objects of a class
) 
# 
 ) 
!$/
) 
# 
 ) 
!$ ;

) 
# ) 
/
Creating objects of a class
) 
# 
 ) 
!$/
) 
# 
 ) 
!$ ;

) 
# ) 
/

Before Assignment Before Assignment

aCircle bCircle aCircle bCircle

P Q P Q
Automatic garbage collection
‡ The object Q does not have a
reference and cannot be used in future.

‡ The object becomes a candidate for


automatic garbage collection.

‡ Java automatically collects garbage


periodically and releases the memory
used to be used in the future.
Accessing Object/Circle Data
‡ Similar to C syntax for accessing data
defined in a structure.

±  
 
,5
( 

( 
! 

$

) 
) 
# 
 ) 
!$/

) 
" # 0 3   4


 
) 
& # 0 3
) 
# 3
Executing Methods in
Object/Circle
‡ sing Object Methods:

 6
 
7  ) 

) 
) 
# 
 ) 
!$/



/
) 
# 3/

# ) 

!$/
—sing Circle Class
// Circle.java: Contains both Circle class and its user class
//Add Circle class code here
class MyMain
{
public static void main(String args[])
{
Circle aCircle; // creating reference
aCircle = new Circle(); // creating object
aCircle.x = 10; // assigning value to data field
aCircle.y = 20;
aCircle.r = 5;
double area = aCircle.area(); // invoking method
double circumf = aCircle.circumference();
System.out.println("Radius="+aCircle.r+" Area="+area);
System.out.println("Radius="+aCircle.r+" Circumference ="+circumf);
}
}
[raj@mundroo]%: java MyMain
Radius=5.0 Area= 8.5
Radius=5.0 Circumference =31.400000000000002
Summary
‡ Classes, objects, and methods are the basic
components used in Java programming.
‡ We have discussed:
± How to define a class
± How to create objects
± How to add data fields and methods to classes
± How to access data fields and methods to classes
Constructor:

A constructor initializes an object immediately upon creation. It has the same


name as the class in which it resides and is syntactically similar to a method.
Once defined, the constructor is automatically called immediately after the
object is created, before the new operator completes. Constructors look a
little strange because they have no return type, not even void. This is
because the implicit return type of a class¶ constructor is the class type itself.
It is the constructor¶s job to initialize the internal state of an object so that the
code creating an instance will have a fully initialized, usable object immediately.
Syntax:
class classname
{
Type instance variable;
Classname(parameterlist) //constructor
{
// definition
}
Type methodname (parameterlist)
{
// definition
}
}
üx: Class Rectangle
{
Int x,y;
Rectangle( )
Val obj
{
X=23;
Y=94; obj

}
}
class Val
{
Public static void main(String args[ ])
{
Rectangle obj=new Rectangle( );
}
}
Polymorphism:

It is the dynamic feature of oops. it is nothing but ability to take more


forms. It is combination of two words known as poly and morphs that
means many forms

jethod o erloading:

A class can contain any number of methods. Methods can take parameters as
input for data manipulation. These parameters are called type signature. Java
permits many methods to have same name, but with different type of signature is
known as method overloading.
Note:
Overloading methods exhibit the concept of polymorphism.
Nested Classes :

The Java programming language allows you to define a class within another
class. Such a class is called a nested class and is illustrated here:
Syntax:
class OuterClass {
...
class NestedClass {
...
}
}

erminology: Nested classes are divided into two categories: static and

non-static. Nested classes that are declared static are simply called static

nested classes. Non-static nested classes are called inner classes.


Static nested class
As with class methods and variables, a static nested class is associated with

its outer class. And like static class methods, a static nested class cannot

refer directly to instance variables or methods defined in its enclosing class

² it can use them only through an object reference.

Syntax:

class OuterClass
{
...
static class StaticNestedClass
{ ... }
class InnerClass
{ ... }
}
Static nested classes are accessed using the enclosing class name:

OuterClass.StaticNestedClass

For example, to create an object for the static nested class, use this syntax:

OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();


Änner Classes :
As with instance methods and variables, an inner class is associated with

an instance of its enclosing class and has direct access to that object's

methods and fields. Also, because an inner class is associated with an

instance, it cannot define any static members itself.

Objects that are instances of an inner class exist . ›  an

instance of the outer class. Consider the following classes:


class OuterClass {
«.
class InnerClass {
«.
}
}
An instance of InnerClass can exist only within an instance of OuterClass and has

direct access to the methods and fields of its enclosing instance. The next figure

illustrates this idea.

Syntax to create object:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();


Vhy —se Nested Classes?

There are several compelling reasons for using nested classes, among them:


It is a way of logically grouping classes that are only used in one place.


It increases encapsulation.


Nested classes can lead to more readable and maintainable code.
Logical grouping of classes² If a class is useful to only one other class, then it

is logical to embed it in that class and keep the two together. Nesting such "helper

classes" makes their package more streamlined.

Increased encapsulation² Consider two top-level classes, A and B, where B

needs access to members of A that would otherwise be declared private. By

hiding class B within class A, A's members can be declared private and B can

access them. In addition, B itself can be hidden from the outside world.

More readable, maintainable code² Nesting small classes within top-level

classes places the code closer to where it is used


Yccess specifiers:

Accessing a variable means getting charge on the value of the variable.


As the sometimes needs to be more confidential, the access to data must
be controlled. Access control is the process of preventing misuse of data
which is confidential.
java provides three keywords called access specifiers to control
access of data, thy are private, public and protected. These private, public
and protected keywords are called access specifiers because they determine
the level of accessibility towards that variable.


Private

Public

protected
Pri ate:

If the access modifier is private, then that variable can be accessed only
with in that class.

Public:

If public is the access modifier then that variable can be accessed by


any class, any package globally.

Protected:

If protected is the access modifier then that variable is allowed to be


accessed not only by the classes and the subclasses of same package
but also by the sub classes of different package.
4riendly or default:

when no access specifier is specified, the member defaults to the limited

version of public known as friendly. The difference between the public access

and friendly access is that public modifier makes fields visible in all class

regardless of their package while the friendly access makes fields visible only

in the same package but not in other packages


he Garbage Collector:

Some object-oriented languages require that you keep track of all the objects

you create and that you explicitly destroy them when they are no longer needed.

Managing memory explicitly is tedious and error-prone. The Java platform

allows you to create as many objects as you want (limited, of course, by what

your system can handle), and you don't have to worry about destroying them.

The Java runtime environment deletes objects when it determines that they are

no longer being used. This process is called garbage collection.


he finalizer  jethod:

Sometimes an object will need to perform some action when it is destroyed. For
example, if an object is holding some non-Java resource such as a file handle or

window character font, then you might want to make sure these resources are freed

before an object is destroyed. To handle such situations, Java provides a mechanism

called finalization. By using finalization, you can define specific actions that will occur

when an object is just about to be reclaimed by the garbage collector.

To add a finalizer to a class, you simply define the finalize( ) method. The Java run

time calls that method whenever it is about to recycle an object of that class
Inside the finalizer  method you will specify those actions that must be

performed before an object is destroyed. The garbage collector runs

periodically, checking for objects that are no longer referenced by any running

state or indirectly through other referenced objects. Right before an asset is

freed, the Java run time calls the finalize( ) method on the object.

The finalize( ) method has this general form:

protected void finalize( )

// finalization code here

}
Änheritance:

Reusability is yet another important feature of OOP. It is always nice if


we would reuse something that already exits rather than trying to
create the same all over again. It would not only save the time and
money but also reduces frustration and increase reliability. For
instance, the reuse of a class that has already been tested, debugged
and used many times can save us the effort of developing and testing
the same again.
once the class has written and tested, it can be adapted
by other programmer to suit their requirements. This is basically done
by creating new class, reusing the properties of the exiting class ones.
The mechanism of deriving a new class form an old one is called
inheritance.
A Super class

Sub class
B

Fig: Single inheritance


A

Fig: Multilevel inheritance


A B

Fig: Multiple inheritance


A

B C D

Fig: hierarchical inheritance


A

B D

Fig: hybrid inheritance


// A simple example of inheritance.

// Create a superclass.

class A
{

int i, j;

void showij()
{

System.out.println("i and j: " + i + " " + j);

}
// Create a subclass by extending class A.

class B extends A
{

int k;

void showk()
{

System.out.println("k: " + k);

void sum()
{
System.out.println("i+j+k: " + (i+j+k));
}

}
class SimpleInheritance
{

public static void main(String args[ ])


{

A superOb = new A();

B subOb = new B();

// The superclass may be used by itself.


superOb.i = 10;
superOb.j = 20;

System.out.println("Contents of superOb: ");


superOb.showij();
System.out.println();
/* The subclass has access to all public members of
its superclass. */

subOb.i = ;
subOb.j = 8;
subOb.k = 9;

System.out.println("Contents of subOb: ");


subOb.showij();
subOb.showk();
System.out.println();

System.out.println("Sum of i, j and k in subOb:");


subOb.sum();
}
}
he output from this program is shown
here:

Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24
†he this Keyword:

Sometimes a method will need to refer to the object that invoked it. To allow this, Java

defines the this keyword. this can be used inside any method to refer to the current object.

That is, this is always a reference to the object on which the method was invoked. You

can use this anywhere a reference to an object of the current class¶ type is permitted.
class A
{

int a,b;
A(int a, int b)
{
this.a=a;
this.b=b;
}

void display()
{

System.out.println("the value of a= "+a);


System.out.println("the value of b= "+b);

}
}
class prog12
{
public static void main(String args[ ])

{
A obj=new A(5,6);
obj.display();
}
}

Output:

the value of a= 5
the value of b= 6
Super:

super acts somewhat like this, e cept that it always refers to

the superclass of the su class in which it is used. †his usage has the following

general form:
super.mem er

Here, mem er can e either a method or an instance varia le.

super is most applica le to situations in which mem er names

of a su class hide mem ers y the same name in the superclass. Consider this simpleclass hierarchy:
// —sing super to overcome name hiding.
class A
{

int i;

// Create a subclass by extending class A.

class B extends A
{

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

B(int a, int b) {

super.i = a; // i in A

i = b; // i in B

}
void show()
{

System.out.println("i in superclass: " + super.i);

System.out.println("i in subclass: " + i);

}
}
class —seSuper
{

public static void main(String args[ ])


{
B subOb = new B(1, 2);

subOb.show();

}
}
This program displays the following:

i in superclass: 1
i in subclass: 2
Vhen Constructors Yre Called:

When a class hierarchy is created, in what order are the constructors for the classes that

make up the hierarchy called? For example, given a subclass called B and a superclass

called A, is A¶s constructor called before B¶s, or vice versa? The answer is that in a class

hierarchy, constructors are called in order of derivation, from superclass to subclass.

Further, since super( ) must be the first statement executed in a subclass¶ constructor,

this order is the same whether or not super( ) is used. If super( ) is not used, then the

default or parameterless constructor of each superclass will be executed. The following

program illustrates when constructors are executed:


// Demonstrate when constructors are called.

// Create a super class.

class A {

A()
{
System.out.println("Inside A's constructor.");
}

// Create a subclass by extending class A.

class B extends A {

B() {
System.out.println("Inside B's constructor.");
}

}
// Create another subclass by extending B.

class C extends B
{

C() {

System.out.println("Inside C's constructor.");


}

class CallingCons
{
public static void main(String args[ ])
{

C c = new C();
}
}
The output from this program is shown here:

Inside A¶s constructor


Inside B¶s constructor
Inside C¶s constructor
jethod O erriding:

In a class hierarchy, when a method in a subclass has the same name and type

signature as a method in its superclass, then the method in the subclass is said to

 "› ›" › ! "" ›"  "

within a subclass, it will always refer to the version of that method defined by the

subclass. The version of the method defined by the superclass will be hidden.

Consider the following:


// Method overriding.

class A
{
int i, j;

A(int a, int b)
{
i = a;
j = b;
}

// display i and j
void show()
{
System.out.println("i and j: " + i + " " + j);
}

class B extends A {
int k;

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

super(a, b);
k = c;

}
// display k ± this overrides show() in A

void show() {
System.out.println("k: " + k);
}

}
class Override {

public static void main(String args[ ])


{
B subOb = new B(1, 2, 3);

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

The output produced by this program is shown here:


k: 3
// —sing run-time polymorphism.

class Figure
{

double dim1;
double dim2;

Figure(double a, double b)
{

dim1 = a;
dim2 = b;

}
double area()
{
System.out.println("Area for Figure is undefined.");
return 0;
}
}
class Rectangle extends Figure
{
Rectangle(double a, double b)
{
super(a, b);
}

// override area for rectangle

double area()
{

System.out.println("Inside Area for Rectangle.");

return dim1 * dim2;


}

class Triangle extends Figure


{
Triangle(double a, double b)
{
super(a, b);
}

// override area for right triangle

double area()
{
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}

}
  8

-
     !  9:$
-
8
 # 
 8
! 3' 3$/

 
# 
 
 
!;' <$/
*  
 # 
 *  
! 3' =$/
8

/

 # /

&
  !>
 > þ 

!$$/

 # /

&
  !>
 > þ 

!$$/

 # /

&
  !>
 > þ 

!$$/
.
.
The output from the program is shown here:

Inside Area for Rectangle.


Area is 45
Inside Area for Triangle.
Area is 40
Area for Figure is undefined.
Area is 0
4inal class:

Inheritance allows creation of sub classes. However, if need arises,


inheritance can be prevented by declaring a class final . A class declared
as final cannot have subclasses

4inal method:

Methods in a class can be prevented from over riding methods in


sub classes. Like final classes, methods can be declared with the
modifier final. Methods declared as final cannot have overriding
methods in the sub classes.
4inal ariables:
Variables can also be declared as final. Final variables are constant. You
cannot assign any new value to them once you have declared them as
final. Final variables must be assigned values while declaring them to be
final. The general form of declaring final variable is :

Final type VariableName = value;

By convection, final variables are declared with uppercase letters.

EX:
Final int PASS_MARK = 40;
Static jethod:

We have so far seen that methods are called on the objects. That is,
methods are called in relation to an instance of a class. Java provides
a mechanism, in which methods can be called without an instance of a
class. Such method are called static methods.

Syntax:
Classname.static_method;
Static class example:

class Statclass
{

static void add(int a, int b)


{
int sum=a+b;
System.out.println("sum of two numbers="+sum);
}

}
class staticdemo
{

public static void main(String a[])


{
Statclass.add(5,4);
}

}
output:

Sum of two numbers=9


Static Variables:

Instance variables of java can also be declared as static. When a variable


is declared as static, it becomes a class variable rather than an object
variable. Static variable can accessed by any part of the program. Even if
any instance is created, the static variable retain the last modified value.
In effect it becomes a global variable
Static Variables example:

class statvar
{
static int i=0,j=0;
void printval()
{
System.out.println(" i = "+i);

System.out.println(" j = "+j);
}

}
class statvardemo
{
public static void main(String a[])
{
statvar obj=new statvar();
System.out.println(" the value of variables in the first object ");

obj.printval();

obj.i=10;
obj.j=20;

System.out.println("value of variables in the second object ");

statvar obj1=new statvar();

obj1.printval();

}
}
Output:

the value of variables in the first object


i=0
j=0
value of variables in the second object
i = 10
j = 20
Ybstract Classes:

There are situations in which you will want to define a super class that declares the

structure of a given abstraction without providing a complete

implementation of every method. That is, sometimes you will want to create a

Super class that only defines a generalized form that will be shared by all of its

subclasses, leaving it to each subclass to fill in the details. Such a class

determines the nature of the methods that the subclasses must implement.

To declare an abstract method, use this general form:

abstract type name(parameter-list);


Any class that contains one or more abstract methods must also be declared

abstract. To declare a class abstract, you simply use the abstract keyword in front of

the class eyword at the beginning of the class declaration. here can be no

objects of an abstract class. hat is, an abstract class cannot be directly

instantiated with the new operator. Such objects would be useless, because an

abstract class is not fully defined Also, you cannot declare abstract constructors,

or abstract static methods. Any sub class of an abstract class must either implement

all of the abstract methods in the super class or be itself declared abstract.
Example:

abstract class A
{
abstract void callme();

void callmetoo()
{

System.out.println("This is a concrete method.");

}
class B extends A
{
void callme()
{
System.out.println( "B's implementation of callme.");
}
}

class AbstractDemo
{
public static void main(String args[ ])
{

B b = new B();
b.callme();
b.callmetoo();

}
Interfaces :

fAn interface is very much like a class with constant values and method
declarations

fThe interface is public or default

fThe methods in an interface are directly are only declared but not
implemented
fImplicitly all the methods in an interface are abstract

fImplicitly all the interface variables are final and static means , in interface
we can assign a value and that value cannot change in the interface and
their implementation classes.
f All the methods and variables are implictly public with their interface
itself is declared as public.

f In all interface methods we are must implemented their implemented


sub class

f Interface is act like as fully abstract class we cannot create object of the
interface

Implementing interface :

‡ Once the interface is defined one or more classes can implement it.

‡ The method that implement interface must be declared as public.

‡ We can use implement key word to implement interface.


Syntax:

Modifier interface interface_name


{
Type var1;
Type var2;
Modifier return_type methodname( type signature)

Modifier return_type methodname( type signature)


}
Example:

interface x {
int x=10;
void display();
}
class y implements x
{
public void display()
{
System.out.println(x*x);
}

}
class iprog
{
public static void main(String args[])
{
y obj=new y() ;
obj.display();
}
}
If the class implements two interfaces that declares same method, then the
same method will be used by the client either interface

Ex:
interface i1{
Void fun();
}
interface i2{
Void fun();
}

class implements i1,i2


{
public void fun()
{
«.
}
}
‡Java does not support multiple inheritance, java does not have more than one

base class.

‡Java indirectly supports the multi inheritance through interface.

Extends interface:
An interface can extend another interface using keyword extends like class.
Ex:
interface i1
{
Void fun1();
}

interface i2 extends i1
{
Void fun2();
}
Packages:

Java allows you to group classes in a collection called a package. Packages are

convenient for organizing your work and for separating your work from code libraries

provided by others.
The standard Java library is distributed over a number of packages,including

java.lang, java.util, java.net, and so on.

The main reason for using packages is to guarantee the uniqueness of class names

Suppose two programmers come up with the bright idea of supplying an

Employee class.
As long as both of them place their class into different packages, then there is no

conflict. In fact, to absolutely guarantee a unique package name

—sing packages:

A class can use all classes from its own package and all public classes from other

packages. You can access the public classes in another package in two ways.

The first is simply to add the full package name in front of every class name.

For example:

java.util.Date today = new java.util.Date();


You can import a specific class or the whole package.

For example, you can import all classes in the java.util package with the statement:

import java.util.*;

Then you can use

Date today = new Date();


without a package prefix. You can also import a specific class inside a package.

import java.util.Date;
—ser defined packages:

The steps involved in user defined packages.


1.Identify the hierarchy in which we would like to place the .class file
Ex: D:\ javaprog >

2.Create a directory which has the same name as that of the package name
Ex: D:\ javaprog \pack>

3.Include the package statement along with the package name in the package
Ex: Package pack;

4.Save the file with public class name along with java extension
Ex: A.java

5.Compile the file to generate the .class file in the same directory.
Example:
D:\ javaprog> md mypack
D:\ javaprog> cd mypack
D:\ javaprog\mypack> edit A.java
package mypack;
public class A
{
public void funa()
{
System.out.println(³I AM IN CLASS A´);
}
}
D:\javaprog\mypack>javac A.java
D:\ javaprog\mypack> edit B.java
package mypack;
public class B
{
public void funb()
{
System.out.println(³I AM IN CLASS B´);
}
}

D:\javaprog\mypack>javac B.java
D:\ javaprog\mypack> edit C.java
package mypack;
public class C
{
public void func()
{
System.out.println(³I AM IN CLASS C´);
}
}
class trial
{
Public static void main (String args[ ])
{
C objec = new C();
objec.func();
}}
D:\ javaprog\mypack> javac C.java
D:\ javaprog\mypack>cd..
D:\ javaprog>edit pack.java
import mypack.*;
public class pack
{
public static void main()
{
A obj=new A();
obj.funa();

B obj1=new B();
obj1.funb();

}
}
D:\ javaprog> javac pack.java
D:\javaprog> java pack.trial //having main method in package ³pack´
Output:
I AM IN CLASS C

D:\ javaprog> java pack //executing pack.java file

Output:
I AM IN CLASS A
I AM IN CLASS B
Classpath:

If the importing package is not in the sub directory then we have to set the
class path.


The class path is an environmental variable set in the operating system
which contains a collection of sub directories where each sub directory
contains a collection of class files.


Once the class pat is set we are able to access classes in the sub
directory from any location in the system.
Example:

D:\softek\javaprog\userpackages\pack>

If the package is in the directory user packages, we have written


java files in softek directory then we have to set class path to
access that package.

D:\softek> set classpath= D:\softek\javaprog\userpackages;


Hierarchy of packages:

In the package hierarchy is denoted by µ . ¶ (dot) of every level


pack1.pack2.pack3 means that pack3 is in pack2 and pack 2 is in pack1.
So we can create sub packages with another package, to access the sub
package we have specify the entire path.
Exception handling:

Errors :
1. Syntax (occur at compile time)
2. Logical (errors occur at runtime)

Compile time error: the error occur at compilation of a program.

Runtime error: the error occur at execution of the program

Exception handling:

the process of handling exception is called exception

handling. when an error occur in a java method, the method creates an

object of type and gives it to the runtime system


Java exception handling is managed via five keywords: try, catch, throw, throws,

and finally. Briefly, here is how they work. Program statements that you want to

monitor for exceptions are contained within a try block. If an exception occurs within

the try block, it is thrown. Your code can catch this exception (using catch) and handle

it in some rational manner. System-generated exceptions are automatically thrown by

the Java run-time system. To manually throw an exception, use the keyword throw.

Any exception that is thrown out of a method must be specified as such by a throws

clause. Any code that absolutely must be executed before a method returns is put in

a finally block.
This is the general form of an exception-handling block:

try {

// block of code to monitor for errors

catch (ExceptionType1 exOb) {

// exception handler for ExceptionType1

catch (ExceptionType2 exOb) {

// exception handler for ExceptionType2

}
finally {

// block of code to be executed before try block ends

—sing try and catch:

To guard against and handle a run-time error, simply enclose the code that you

want to monitor inside a try block. Immediately following the try block, include a catch

clause that specifies the exception type that you wish to catch
Example:
class Exc2 {

public static void main(String args[ ]) {

int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");

}
catch (ArithmeticException e) {
// catch divide-by-zero error
System.out.println("Division by zero.");

System.out.println("After catch statement.");

}
}
Output:

Division by zero.
After catch statement.
Multiple catch Clauses:

In some cases, more than one exception could be raised by a single piece of code. To

handle this type of situation, you can specify two or more catch clauses, each catching

a different type of exception. When an exception is thrown, each catch statement is

inspected in order, and the first one whose type matches that of the exception is

executed. After one catch statement executes, the others are bypassed, and execution

continues after the try/catch block


Example:
class MultiCatch {

public static void main(String args[]) {

try {

int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[ ] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e) {

System.out.println("Divide by 0: " + e);


}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}

System.out.println("After try/catch blocks.");


}
}
output:
C:\>java MultiCatch

a=0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.

C:\>java MultiCatch TestArg

a=1
Array index oob:
java.lang.ArrayIndexOutOfBoundsException
After try/catch blocks.
Nested try Statements:

The try statement can be nested. That is, a try statement can be inside the block of

another try. Each time a try statement is entered, the context of that exception is

pushed on the stack. If an inner try statement does not have a catch handler for a

particular exception, the stack is unwound and the next try statement¶s catch handlers

are inspected for a match. This continues until one of the catch statements succeeds, or

until all of the nested try statements are exhausted. If no catch statement matches, then

the Java run-time system will handle the exception


example:

class NestTry {

public static void main(String args[ ]) {

try {

int a = args.length;

/* If no command-line args are present,


the following statement will generate
a divide-by-zero exception. */

int b = 42 / a;

System.out.println("a = " + a);


try { // nested try block

/* If one command-line arg is used,


then a divide-by-zero exception
will be generated by the following code. */

if(a==1) a = a/(a-a);

// division by zero

/* If two command-line args are used,


then generate an out-of-bounds exception. */
if(a==2) {

int c[ ] = { 1 };

c[42] = 99; // generate an out-of-bounds exception


}
}
catch(ArrayIndexOutOfBoundsException e) {

System.out.println("Array index out-of-bounds: " + e);


}
}
catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}
C:\>java NestTry

Divide by 0: java.lang.ArithmeticException: / by zero

C:\>java NestTry One


a=1
Divide by 0: java.lang.ArithmeticException: / by zero

C:\>java NestTry One Two


a=2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException
Throw:
So far, you have only been catching exceptions that are thrown by the Java run-time

system. However, it is possible for your program to throw an exception explicitly,

using the throw statement. The general form of throw is shown here:

throw ThrowableInstance;

Here, ThrowableInstance must be an object of type Throwable or a


subclass of Throwable.
Example:

class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
}
catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
}
catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}
Output:

Caught inside demoproc.

Recaught: java.lang.NullPointerException: demo


throws:

If a method is capable of causing an exception that it does not handle, it must specify

this behavior so that callers of the method can guard themselves against that exception.

You do this by including a throws clause in the method¶s declaration. A throws clause

lists the types of exceptions that a method might throw. This is necessary for all

exceptions, except those of type Error or RuntimeException, or any of their subclasses.

All other exceptions that a method can throw must be declared in the throws clause. If

they are not, a compile-time error will result.


This is the general form of a method declaration that includes a throws clause:

› ›"/  ›/ › ›.( › / ›

// body of method

}
Example:

class ThrowsDemo {

static void throwOne() throws IllegalAccessException


{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}

public static void main(String args[]) {

try {
throwOne();
}
catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}

}
}
output:

inside throwOne
caught java.lang.IllegalAccessException: demo
Finally:

In try and catch block all statements are executed, if no such exceptions occurs.

When an exception occurs, the statements placed in between the point of

occurring Of the exception and end of the blocked will be skipped and the

control looks for matching a catch block. In certain problems, it is essential to

execute certain statements, such statements are placed in finally block.

Example:
class FinallyDemo {
// Through an exception out of the method.
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
}
finally {
System.out.println("procA's finally");
}
}
// Return from within a try block.
static void procB() {
try {
System.out.println("inside procB");
return;
}
finally

{
System.out.println("procB's finally");
}

// Execute a try block normally.


static void procC() {
try {
System.out.println("inside procC");
} finally {
System.out.println("procC's finally");
}
}
public static void main(String args[]) {
try {
procA();
} catch (Exception e) {
System.out.println("Exception caught");
}
procB();
procC();
}
}

Output:

inside procA
procA's finally
Exception caught
inside procB
procB's finally
inside procC
procC's finally
julti hreading:
A multithreaded program contains two or more parts that can run concurrently.

Each part of such a program is called a thread, and each thread defines a

separate path of execution. Thus, multithreading is a specialized form of

multitasking
julti hreading:

You are almost certainly acquainted with multitasking, because it is supported

by virtually all modern operating systems. However, there are two distinct types

of multitasking: process-based and thread-based. It is important to understand the

difference between the two. For most readers, process-based multitasking is the more

familiar form. A process is, in essence, a program that is executing. Thus, process-based

multitasking is the feature that allows your computer to run two or more programs

concurrently.

For example, process-based multitasking enables you to run the Java

compiler at the same time that you are using a text editor. In process-based multitasking,

a program is the smallest unit of code that can be dispatched by the scheduler.
In a thread-based multitasking environment, the thread is the smallest unit of

dispatchable code. This means that a single program can perform two or more tasks

simultaneously. For instance, a text editor can format text at the same time that it is

printing, as long as these two actions are being performed by two separate threads.

Thus, process-based multitasking deals with the ³big picture,´ and thread-based

multitasking handles the details.


Multithreading enables you to write very efficient programs that make maximum

use of the CP—, because idle time can be kept to a minimum. This is especially

important for the interactive, networked environment in which Java operates, because

idle time is common. For example, the transmission rate of data over a network is

much slower than the rate at which the computer can process it. Even local file system

resources are read and written at a much slower pace than they can be processed by the

CP—. And, of course, user input is much slower than the computer. In a traditional,

single-threaded environment, your program has to wait for each of these tasks to finish

before it can proceed to the next one²even though the CP— is sitting idle most of the

time. Multithreading lets you gain access to this idle time and put it to good use
he Ja a hread jodel:

The Java run-time system depends on threads for many things, and all the class libraries

are designed with multithreading in mind. In fact, Java uses threads to enable the

entire environment to be asynchronous. This helps reduce inefficiency by preventing

the waste of CP— cycles.


Vhat Äs a hread?:

A thread executes a series of instructions. Every line of code that is executed is

done so by a thread. Some threads can run for the entire life of the applet,

while others are alive for only a few milliseconds. A thread also creates a new

thread or kills an existing one. Threads run in methods or constructors. The

methods and constructors themselves are lifeless. The threads go into the

methods and follow their instructions. Methods and constructors reside in the

computer's memory
Threads ± Thread States
‡ State diagram
new start
notify, notifyYll,
new runnable
ÄO complete,
sleep expired,
yield,
scheduler join complete
time
slice
running bloc ed
ÄO, sleep,
terminate wait, join

dead
Threads exist in several states. A thread can be running.It can be ready to run as

soon as it gets CP— time. A running thread can be suspended, which temporarily

suspends its activity. A suspended thread can then be resumed, allowing it to pick up

where it left off. A thread can be blocked when waiting for a resource. At any time, a

thread can be terminated, which halts its execution immediately. Once terminated, a

thread cannot be resumed


he hread Class and the unnable Änterface:

Java¶s multithreading system is built upon the Thread class, its methods, and its

companion interface, Runnable. Thread encapsulates a thread of execution. Since

you can¶t directly refer to the ethereal state of a running thread, you will deal with it

through its proxy, the Thread instance that spawned it. To create a new thread, your

program will either extend Thread or implement the Runnable interface. The Thread

class defines several methods that help manage threads. The ones that will be used in

this chapter are shown here:


Method Meaning

getName Obtain a thread¶s name.

getPriority Obtain a thread¶s priority.

isAlive Determine if a thread is still running.

join Wait for a thread to terminate.

run Entry point for the thread.

sleep Suspend a thread for a period of time.

start Start a thread by calling its run method


Creating a hread:

In the most general sense, you create a thread by instantiating an object of type Thread.

Java defines two ways in which this can be accomplished:

You can implement the Runnable interface.

You can extend the Thread class, itself.


Ämplementing unnable:
class NewThread implements Runnable
{
Thread t;
NewThread()
{
// Create a new, second thread

t = new Thread(this, "Demo Thread");

System.out.println("Child thread: " + t);

t.start(); // Start the thread


}

// This is the entry point for the second thread.

public void run() {


try {
for(int i = 5; i > 0; i--)
{
System.out.println("Child Thread: " + i);

Thread.sleep(500);

}
}
catch (InterruptedException e)

System.out.println("Child interrupted.");

}
System.out.println("Exiting child thread.");

}
}
class ThreadDemo
{
public static void main(String args[ ])
{

new NewThread(); // create a new thread


try
{

for(int i = 5; i > 0; i--)


{

System.out.println("Main Thread: " + i);

Thread.sleep(1000);
}
}
catch (InterruptedException e)

System.out.println("Main thread interrupted.");

System.out.println("Main thread exiting.");

}
}

Inside NewThread ¶s constructor, a new Thread object is created by the

following statement:

t = new Thread(this, "Demo Thread");


Passing this as the first argument indicates that you want the new thread to call the

run( ) method on this object. Next, start( ) is called, which starts the thread of execution

beginning at the run( ) method. This causes the child thread¶s for loop to begin. After

calling start( ) , NewThread ¶s constructor returns to main( ) . When the main thread

resumes, it enters its for loop.


Both threads continue running, sharing the CP—, until

their loops finish. The output produced by this program is as follows:

Child thread: Thread[Demo Thread,5,main]

Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting
üxtending hread:

The second way to create a thread is to create a new class that extends Thread ,

and then to create an instance of that class. The extending class must override the

run( ) method, which is the entry point for the new thread. It must also call start( )

to begin execution of the new thread. Here is the preceding program rewritten to

extend Thread :
// Create a second thread by extending Thread

class NewThread extends Thread


{
NewThread()
{

// Create a new, second thread

super("Demo Thread");

System.out.println("Child thread: " + this);

start(); // Start the thread

}
// This is the entry point for the second thread.

public void run()


{
try {

for(int i = 5; i > 0; i--)


{
System.out.println("Child Thread: " + i);

Thread.sleep(500);

} catch (InterruptedException e)
{
System.out.println("Child interrupted.");
}

System.out.println("Exiting child thread.");


}
}
class ExtendThread
{
public static void main(String args[])
{

new NewThread();

// create a new thread


try
{
for(int i = 5; i > 0; i--)
{
System.out.println("Main Thread: " + i);

Thread.sleep(1000);

}
}
} catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}

This program generates the same output as the preceding version. As you can

see, thechild thread is created by instantiating an object of NewThread , which is

derived fromThread . Notice the call to super( ) inside NewThread . This invokes

the following form of the Thread constructor: public Thread(String threadName )

Here, threadName specifies the name of the thread


Creating jultiple hreads:
// Create multiple threads.

class NewThread implements Runnable


{
String name; // name of thread

Thread t;

NewThread(String threadname)
{
name = threadname;

t = new Thread(this, name);

System.out.println("New thread: " + t);

t.start(); // Start the thread


}
// This is the entry point for thread.

public void run()


{

try {

for(int i = 5; i > 0; i--)


{
System.out.println(name + ": " + i);

Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println(name + "Interrupted");

}
System.out.println(name + " exiting.");

}
}

class MultiThreadDemo {
public static void main(String args[])
{
new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");

try {
// wait for other threads to end
Thread.sleep(10000);
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");

System.out.println("Main thread exiting.");

}
The output from this program is shown here:
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
One: 5
Two: 5
Three: 5
One: 4
Two: 4
Three: 4
One: 3
Three: 3
Two: 3
One: 2
Three: 2
Two: 2
One: 1
Three: 1
Two: 1
One exiting.
Two exiting.
Three exiting.
Main thread exiting.

As you can see, once started, all three child threads share the CP—. Notice the call to

sleep(10000) in main( ) . This causes the main thread to sleep for ten seconds and

ensures that it will finish last.


—sing isYli er  and joinr :

Two ways exist to determine whether a thread has finished. First, you can call
isAlive( ) on the thread. This method is defined by Thread , and its general form is
shown here:

final boolean isAlive( )

The isAlive( ) method returns true if the thread upon which it is called is still running. It

returns false otherwise. WhileisAlive( ) is occasionally useful, the method that you will

more commonly use to wait for a thread to finish is called join( ) , shown here:

final void join( ) throws InterruptedException


This method waits until the thread on which it is called terminates. Its name comes

from the concept of the calling thread waiting until the specified thread joins it.

Additional forms of join( ) allow you to specify a maximum amount of time that

you want to wait for the sp ecified thread to terminate.


class NewThread implements Runnable
{
String name; // name of thread

Thread t;

NewThread(String threadname)
{
name = threadname;

t = new Thread(this, name);

System.out.println("New thread: " + t);

t.start(); // Start the thread


}
// This is the entry point for thread.
public void run()
{
try {

for(int i = 5; i > 0; i--)


{
System.out.println(name + ": " + i);

Thread.sleep(1000);

}
catch (InterruptedException e)
{
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
}
class DemoJoin
{
public static void main(String args[ ])
{
NewThread ob1 = new NewThread("One");

NewThread ob2 = new NewThread("Two");

NewThread ob3 = new NewThread("Three");

System.out.println("Thread One is alive: "+ ob1.t.isAlive());

System.out.println("Thread Two is alive: "+ ob2.t.isAlive());

System.out.println("Thread Three is alive: "+ ob3.t.isAlive());


// wait for threads to finish
try
{
System.out.println("Waiting for threads to finish.");
ob1.t.join();

ob2.t.join();

ob3.t.join();

}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");

System.out.println("Thread One is alive: "+ ob1.t.isAlive());

System.out.println("Thread Two is alive: "+ ob2.t.isAlive());

System.out.println("Thread Three is alive: "+ ob3.t.isAlive());

System.out.println("Main thread exiting.");

}
Sample output from this program is shown here:
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
Thread One is alive: true
Thread Two is alive: true
Thread Three is alive: true
Waiting for threads to finish.
One: 5
Two: 5
Three: 5
One: 4
Two: 4
Three: 4
One: 3
Two: 3
Three: 3
One: 2
Two: 2
Three: 2
One: 1
Two: 1
Three: 1
Two exiting.
Three exiting.
One exiting.
Thread One is alive: false
Thread Two is alive: false
Thread Three is alive: false
Main thread exiting.
hread Priorities :
To set a thread¶s priority, use the setPriority( ) method, which is a member of Thread.

This is its general form:

final void setPriority(int level )

Here, level specifies the new priority setting for the calling thread.

The value of level must be within the range MIN_PRIORITY and

MAX_PRIORITY . Currently, thesevalues are 1 and 10, respectively.

To return a thread to default priority, specify NORM_PRIORITY,

which is currently 5. These priorities are defined as final variables

within Thread
You can obtain the current priority setting by calling the getPriority( ) method of

Thread , shown here:

final int getPriority( )


class clicker implements Runnable
{
int click = 0;
Thread t;

private volatile boolean running = true;

public clicker(int p)

{
t = new Thread(this);

t.setPriority(p);
}

public void run() {


while (running) {
click++;
}
}
public void stop()
{
running = false;
}
public void start()
{

t.start();

}
}

class HiLoPri
{
public static void main(String args[ ])
{
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
clicker hi = new clicker(Thread.NORM_PRIORITY + 2);
clicker lo = new clicker(Thread.NORM_PRIORITY - 2);
lo.start();
hi.start();
try {
Thread.sleep(10000);

} catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");

lo.stop();

hi.stop();

// Wait for child threads to terminate.

Try
{
hi.t.join();
lo.t.join();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Low-priority thread: " + lo.click);

System.out.println("High-priority thread: " + hi.click);

}
Synchronization:

When two or more threads need access to a shared resource, they need some way to

ensure that the resource will be used by only one thread at a time. The process by

which this is achieved is called synchronization


class syn
{
static synchronized void method(String s)
{
for(int i=0;i<=10;i++)
{
System.out.println(s+i);
}
try
{
Thread.sleep(10);
}
catch(Exception e)
{
}
}
}
class Th1 extends Thread
{
public void run()
{
syn.method("FIRST THREAD");
}
}
class Th2 extends Thread
{
public void run()
{
syn.method("SECOND THREAD");
}
}
class MainThread
{
public static void main(String args[])
{
Th1 obj1=new Th1();
Th2 obj2=new Th2();
obj1.start();
obj2.start();
}
}
O—TP—T:
FIRST THREAD0
FIRST THREAD1
FIRST THREAD2
FIRST THREAD3
FIRST THREAD4
FIRST THREAD5
FIRST THREAD6
FIRST THREAD
FIRST THREAD8
FIRST THREAD9
FIRST THREAD10
SECOND THREAD0
SECOND THREAD1
SECOND THREAD2
SECOND THREAD3
SECOND THREAD4
SECOND THREAD5
SECOND THREAD6
SECOND THREAD
SECOND THREAD8
SECOND THREAD9
SECOND THREAD10
YV: Y SYC VÄNDOV OOL KÄ:

It is a collection of classes which provide graphical component such as


buttons,textboxes,text fields,labels etc.

It is combining classes used in java.awt package

Component class
This is a super of all components, it is providing a set of methods
which available in sub class.
The AWT supports the following types of controls:

Ŷ Labels
Ŷ Push buttons
Ŷ Check boxes
Ŷ Choice lists
Ŷ Lists
Ŷ Scroll bars
Ŷ Text editing

These controls are subclasses of Component


Labels:
The easiest control to use is a label. A 0is an object of type Label,

and it contains a string, which it displays. Labels are passive controls that

do not support any interaction with the user. Label defines the following

constructors:

Label( )
Label(String ›)
Label(String ›, int .)

The first version creates a blank label. The second version creates a

label that contains the string specified by ›This string is left-justified.

The third version creates a label that contains the string specified by ›

using the alignment specified by .The value of .must be one of

these three constants: Label.Lü4, Label.ÄGH, or Label.CüNü.


You can set or change the text in a label by using the setextr  method. You can
obtain the current label by calling getextr . These methods are shown here:

void setText(String ›)


String getText( )

For setextr , ›specifies the new label. For getextr , the current label is

returned. You can set the alignment of the string within the label by calling

setYlignmentr .To obtain the current alignment, call getYlignmentr . The


methods are as follows:

void setAlignment(int .)

int getAlignment( )
import java.awt.*;
import java.awt.event.*;
class myf extends Frame
{
public myf()
{
setVisible(true);
setSize(400,500);

setLayout(new FlowLayout(FlowLayout.LEFT));

Label one = new Label("One");


Label two = new Label("Two");
Label three = new Label("Three");
add(one);
add(two);
add(three);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
setVisible(false);
System.exit(0);
}
});

}
}
class mylabel
{
public static void main(String args[])
{
myf obj=new myf();
}
}

To execute the program:


Javac mylabel.java

Java mylabel
—sing Buttons:

The most widely used control is the push button. A 0››is a component
that contains a label and that generates an event when it is pressed. Push
buttons are objects of type utton. utton defines these two constructors:

Button( )
Button(String ›)

The first version creates an empty button. The second creates a button that
contains ›as a label.
After a button has been created, you can set its label by calling
setLabelr . You can retrieve its label by calling getLabelr . These methods
are as follows:

void setLabel(String ›)


String getLabel( )

Here, ›becomes the new label for the button.


Ypplying Chec oxes:

A  10(is a control that is used to turn an option on or off. It consists of


a small box that can either contain a check mark or not. There is a label
associated with each check box that describes what option the box
represents. You change the state of a check box by clicking on it. Check
boxes can be used individually or as part of a group. Check
boxes are objects of the Chec box class.

Chec box supports these constructors:

Checkbox( )

Checkbox(String ›)

Checkbox(String ›, boolean )

Checkbox(String ›, boolean , CheckboxGroup 02)

Checkbox(String ›, CheckboxGroup 02, boolean )


The first form creates a check box whose label is initially blank. The state

of the check box is unchecked. The second form creates a check box

whose label is specified by ›The state of the check box is unchecked.

The third form allows you to set the initial state of the check box. If is

true, the check box is initially checked; otherwise, it is cleared. The fourth

and fifth forms create a check box whose label is specified by ›and

whose group is specified by 02If this check box is not part of a

group, then 02must be null. (Check box groups are described in the

next section.) The value of determines the initial state of the check box.
To retrieve the current state of a check box, call getStater . To set its

state, call setStater . You can obtain the current label associated with a

check box by calling getLabelr . To set the label, call setLabelr .

These methods are as follows:

boolean getState( )

void setState(boolean )

String getLabel( )

void setLabel(String ›)

Here, if is true, the box is checked. If it is false, the box is cleared.
The string passed in ›becomes the new label associated with the
invoking check box.
—sing a TextField:

The ext4ield class implements a single-line text-entry area, usually called an

" › ›Text fields allow the user to enter strings and to edit the text using

the arrow keys, cut and paste keys, and mouse selections. ext4ield is a

subclass of extComponent. ext4ield defines the following constructors:

TextField( )

TextField(int  )

TextField(String ›)

TextField(String ›, int  )


The first version creates a default text field. The second form creates a text

field that is  characters wide. The third form initializes the text field

with the string contained in ›The fourth form initializes a text field and sets

its width.ext4ield (and its superclass extComponent) provides several

methods that allow you to utilize a text field. To obtain the string currently

contained in the text field, call getextr . To set the text, call setextr .

These methods are as follows:

String getText( )

void setText(String ›)

Here, ›is the new string.


—sing a TextArea:

Sometimes a single line of text input is not enough for a given task. To handle these
situations, the AWT includes a simple multiline editor called extYrea. Following are
the constructors for extYrea:

TextArea( )

TextArea(int   3int  )

TextArea(String ›)

TextArea(String ›, int   , int  )

TextArea(String ›, int   , int  , int 4)


Here,   specifies the height, in lines, of the text area, and

 specifies its width, in characters. Initial text can be

specified by ›In the fifth form you can specify the scroll bars that

you want the control to have. 4must be one of these values:

SCROLLBARS_BOTH SCROLLBARS_NONE

SCROLLBARS_HORIZONTAL_ONLY

SCROLLBARS_VERTICAL_ONLY
Applet:

An Applet is a program designed in java and will be placed in the sever.

The Applet will be downloaded in the server to the client doing with the HTML

Document and run in the client web browser. An Applet can contain component

like,checkboxes radio buttons etc.applet can open network program


Applet Initialization and Termination:

It is important to understand the order in which the various methods


shown in the skeleton are called. When an applet begins, the AWT
calls the following methods, in this sequence:

. initr 

2. startr 

3. paintr 

When an applet is terminated, the following sequence of method calls takes place:

. stopr 

2. destroyr 
init( )

The initr  method is the first method to be called. This is where you should

initialize variables. This method is called only once during the run time of your

applet.

start( )

The startr  method is called after initr . It is also called to restart an applet

after it has been stopped. Whereas initr  is called once²the first time an

applet is loaded²startr  is called each time an applet¶s HTML document is

displayed onscreen. So, if a user leaves a web page and comes back, the

applet resumes execution at startr .


paint( )

The paintr  method is called each time your applet¶s output must be redrawn. This

situation can occur for several reasons. For example, the window in which the

applet is running may be overwritten by another window and then uncovered. Or

the applet window may be minimized and then restored. paintr  is also called

when the applet begins execution. Whatever the cause, whenever the applet must

redraw its output, paintr  is called. The paintr  method has one parameter of

type Graphics. This parameter will contain the graphics context, which describes

the graphics environment in which the applet is running. This context is used

whenever output to the applet is required.


stop( )

The stopr  method is called when a web browser leaves the HTML

document containing the applet²when it goes to another page, for

example. When stopr  is called, the applet is probably running. You

should use stopr  to suspend threads that don¶t need to run when the

applet is not visible. You can restart them when startr  is called if the

user returns to the page


destroy( )

The destroyr  method is called when the environment determines that

your applet needs to be removed completely from memory. At this point,

you should free up any resources the applet may be using. The stopr 

method is always called before destroyr .


import java.awt.*;
import java.applet.*;
/*
<applet code="AppletSkel" width=300 height=100>
</applet>
*/
public class AppletSkel extends Applet {
// Called first.
public void init() {
// initialization
}
/* Called second, after init(). Also called whenever
the applet is restarted. */
public void start() {
// start or resume execution
}
// Called when the applet is stopped.
public void stop() {
// suspends execution
}

/* Called when applet is terminated. This is the last


method executed. */

public void destroy() {


// perform shutdown activities
}

// Called when an applet's window must be restored.

public void paint(Graphics g) {


// redisplay contents of window
}
}
/*
<applet code="AppletSkel" width=300 height=100>
</applet>
*/

To compile : javac filename.java

To execute: appletviewer filename.java

The above code must be inserted to execute the applet or u can use

Applet tag in html document


<HTML>
<HEAD></HEAD>

<BODY>

<APPLET CODE=³FILENAME´ HEIGHT=³ ³ WIDTH=³ ³></APPLET>

</BODY>

</HTML>
Drawing Lines:

Lines are drawn by means of the drawLiner  method, shown here:

void drawLine(int ››5, int ››6, int "5, int "6)

drawLiner  displays a line in the current drawing color that begins

at ››5,››6and ends at "5,"6.


// Draw lines
import java.awt.*;
import java.applet.*;
/*
<applet code="Lines" width=300 height=200>
</applet>
*/
public class Lines extends Applet
{
public void paint(Graphics g)
{
g.drawLine(0, 0, 100, 100);

g.drawLine(0, 100, 100, 0);

g.drawLine(40, 25, 250, 180);

g.drawLine( 5, 90, 400, 400);

g.drawLine(20, 150, 400, 40);

g.drawLine(5, 290, 80, 19);


}
}
Drawing Rectangles:

The drawectr  and fillectr  methods display an outlined and filled


rectangle, respectively. They are shown here:

void drawRect(int ›, int ›, int . "›, int  ›)


void fillRect(int ›, int ›, int . "›, int  ›)

The upper-left corner of the rectangle is at ›,›The dimensions of the


rectangle are specified by . "›and  ›

To draw a rounded rectangle, use drawoundectr  or filloundectr ,


both shown here:

void drawRoundRect(int ›, int ›, int . "›, int  ›,int (7  , int 7  )

void fillRoundRect(int ›, int ›, int . "›, int  ›,int (7  , int 7  )
// Draw rectangles
import java.awt.*;
import java.applet.*;
/*
<applet code="Rectangles" width=300 height=200>
</applet>
*/
public class Rectangles extends Applet
{
public void paint(Graphics g)
{
g.drawRect(10, 10, 60, 50);
g.fillRect(100, 10, 60, 50);
g.drawRoundRect(190, 10, 60, 50, 15, 15);
g.fillRoundRect( 0, 90, 140, 100, 30, 40);
}
}
Drawing Ellipses and Circles

To draw an ellipse, use drawO alr . To fill an ellipse, use fillO alr .
These methods are shown here:

void drawOval(int ›, int ›, int . "›, int  ›)


void fillOval(int ›, int ›, int . "›, int  ›)

// Draw Ellipses
import java.awt.*;
import java.applet.*;
/*
<applet code="Ellipses" width=300 height=200>
</applet>
*/
public class Ellipses extends Applet {
public void paint(Graphics g) {
g.drawOval(10, 10, 50, 50);
g.fillOval(100, 10, 5, 50);
g.drawOval(190, 10, 90, 30);
g.fillOval( 0, 90, 140, 100);
}
}
Drawing Arcs:

Arcs can be drawn with drawYrcr  and fillYrcr , shown here:

void drawArc(int ›, int ›, int . "›, int  ›, int ››#,int .#)

void fillArc(int ›, int ›, int . "›, int  ›, int ››#,int .#)
// Draw Arcs
import java.awt.*;
import java.applet.*;
/*
<applet code="Arcs" width=300 height=200>
</applet>
*/
public class Arcs extends Applet {
public void paint(Graphics g) {
g.drawArc(10, 40, 0, 0, 0, 5);
g.fillArc(100, 40, 0, 0, 0, 5);
g.drawArc(10, 100, 0, 80, 0, 1 5);
g.fillArc(100, 100, 0, 90, 0, 2 0);
g.drawArc(200, 80, 80, 80, 0, 180);
}
}
Drawing Polygons:

It is possible to draw arbitrarily shaped figures using drawPolygonr  and

fillPolygonr ,shown here:

void drawPolygon(int ([ ], int [ ], int   ›)

void fillPolygon(int ([ ], int [ ], int   ›)


// Draw Polygon
import java.awt.*;
import java.applet.*;
/*
<applet code="HourGlass" width=230 height=210>
</applet>
*/
public class HourGlass extends Applet {
public void paint(Graphics g) {
int xpoints[] = {30, 200, 30, 200, 30};
int ypoints[] = {30, 30, 200, 200, 30};
int num = 5;
g.drawPolygon(xpoints, ypoints, num);
}
}
Setting the Current Graphics Color

By default, graphics objects are drawn in the current foreground color. You
can change this color by calling the Graphics method setColorr :

void setColor(Color . )

Here, . specifies the new drawing color.


You can obtain the current color by calling getColorr , shown here:

Color getColor( )
// Demonstrate color.
import java.awt.*;
import java.applet.*;
/*
<applet code="ColorDemo" width=300 height=200>
</applet>
*/
public class ColorDemo extends Applet {
// draw lines

public void paint(Graphics g)


{
Color c1 = new Color(255, 100, 100);
Color c2 = new Color(100, 255, 100);
Color c3 = new Color(100, 100, 255);
g.setColor(c1);

g.drawLine(0, 0, 100, 100);

g.drawLine(0, 100, 100, 0);

g.setColor(c2);

g.drawLine(40, 25, 250, 180);

g.drawLine( 5, 90, 400, 400);

g.setColor(c3);

g.drawLine(20, 150, 400, 40);

g.drawLine(5, 290, 80, 19);


g.setColor(Color.red);

g.drawOval(10, 10, 50, 50);

g.fillOval( 0, 90, 140, 100);

g.setColor(Color.blue);

g.drawOval(190, 10, 90, 30);

g.drawRect(10, 10, 60, 50);

g.setColor(Color.cyan);

g.fillRect(100, 10, 60, 50);

g.drawRoundRect(190, 10, 60, 50, 15, 15);


}
}
—nderstanding Layout Managers:

Each Container object has a layout manager associated with it. A layout
manager is an instance of any class that implements the Layoutjanager
interface. The layout manager is set by the setLayoutr  method. If no call
to setLayoutr  is made, then the default layout manager is used.
Whenever a container is resized (or sized for the first time), the layout
manager is used to position each of the components within it. The
setLayoutr  method has the following general form:

void setLayout(LayoutManager ›80$)

Here, ›80$is a reference to the desired layout manager. If you wish to disable

the layout manager and position components manually, pass null for ›80$If

you do this, you will need to determine the shape and position of each component

manually, using the set oundsr  method defined by Component. Normally, you

will want to use a layout manager.


FlowLayout:

4lowLayout is the default layout manager. This is the layout manager that
the preceding examples have used. 4lowLayout implements a simple
layout style, which is similar to how words flow in a text
editor.Components are laid out from the upper-left corner, left to right and
top to bottom. When no more components fit on a line, the next one
appears on the next line. A small space is left between each component,
above and below, as well as left and right.
Here are the constructors for 4lowLayout:

FlowLayout( )

FlowLayout(int .)

FlowLayout(int ., int , int ›)


The first form creates the default layout, which centers components and

leaves five pixels of space between each component. The second form lets

you specify how each line is aligned. Valid values for .are as follows:

FlowLayout.LEFT

FlowLayout.CENTER

FlowLayout.RIGHT

These values specify left, center, and right alignment, respectively. The third form

allows you to specify the horizontal and vertical space left between components

in and ›3respectively.
BorderLayout:

The orderLayout class implements a common layout style for top-level

windows. It has four narrow, fixed-width components at the edges and one

large area in the center. The four sides are referred to as north, south,

east, and west. The middle area is called the center. Here are the

constructors defined by orderLayout:

BorderLayout( )

BorderLayout(int , int ›)


The first form creates a default border layout. The second allows you to

specify the horizontal and vertical space left between components in

and ›3respectively. orderLayout defines the following

constants that specify the regions:

BorderLayout.CENTER BorderLayout.SO—TH

BorderLayout.EAST BorderLayout.WEST

BorderLayout.NORTH
When adding components, you will use these constants with the following form of

addr , which is defined by Container:

void add(Component  80$3Object  );

Here,  80$is the component to be added, and  specifies where the
component will be added.
GridLayout:

GridLayout lays out components in a two-dimensional grid. When you


instantiate a GridLayout, you define the number of rows and columns.
The constructors supported by GridLayout are shown here:

GridLayout( )

GridLayout(int  9., int   )

GridLayout(int  9., int   , int , int ›)

The first form creates a single-column grid layout. The second form
creates a grid layout with the specified number of rows and columns. The
third form allows you to specify the horizontal and vertical space left
between components in and ›, respectively. Either  9.or
  can be zero. Specifying  9.as zero allows for
unlimited-length columns. Specifying   as zero allows for
unlimited-length rows.
Card Layout:

The card layout is a set of cards will be added to the layout each card

Contains any number of components. To create a card panel will be used. Whenever

a card is selected by the user the components of that card will be on applet

CardLayout( )

CardLayout(int , int ›)


—se of a card layout requires a bit more work than the other layouts. The

cards are typically held in an object of type Panel. This panel must have

CardLayout selected as its layout manager. The cards that form the deck

are also typically objects of type Panel. Thus, you must create a panel that

contains the deck and a panel for each card in the deck. Next, you add to

the appropriate panel the components that form each card. You then add

these panels to the panel for which CardLayout is the layout manager.

Finally, you add this panel to the main applet panel. Once these steps are

complete, you must provide some way for the user to select between cards.

One common approach is to include one push button for each card in the

deck.
When card panels are added to a panel, they are usually given a name.
Thus, most of the time, you will use this form of addr  when adding
cards to a panel:

void add(Component 80$3Object  );

Here,  is a string that specifies the name of the card whose panel

is specified by 80$.

Вам также может понравиться