Академический Документы
Профессиональный Документы
Культура Документы
What is java?
Based on C/C++
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
!
"
#
VV
"$
%
%
U |&''())*'
Getting Started: (2)
r Compile the program:
± compile HelloWorldApp.java by using the following command:
V
V
± 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
± "% " &'( )
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
r U ic e c aracter
Precedence of Arithmetic operators
± erator(s) ± eratio (s) ±r er of eval atio ( rece e ce)
4
à
±
þ þ þ
à
Integer Variables
M ri ti M ri ti
È l
È 4
È * ÈÈ +
È
È X +
üscape sequences e amples
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";
R
> >( is greater than (
à
( is less than (
boolean expressions,
,
8
they are also called
Boolean Operators. 88 ,
,
"
(
"
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
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 "
)
-
"' &/
/
"' &/
/
!$ -
01
2/
.
!$ -
1
2 / Method Body
.
.
Data Abstraction
Declare the Circle class, have created a
new data type ± Data Abstraction
)
)
/
)
)
/
Class of Circle cont.
aCircle, bCircle simply refers to a Circle
object, not an object itself.
)
)
null null
)
# )
/
Creating objects of a class
)
#
)
!$/
)
#
)
!$ ;
)
# )
/
P Q P Q
Automatic garbage collection
The object Q does not have a
reference and cannot be used in future.
±
,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:
}
}
class Val
{
Public static void main(String args[ ])
{
Rectangle obj=new Rectangle( );
}
}
Polymorphism:
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
its outer class. And like static class methods, a static nested class cannot
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:
an instance of its enclosing class and has direct access to that object's
direct access to the methods and fields of its enclosing instance. The next figure
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
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.
Private
Public
protected
Pri ate:
If the access modifier is private, then that variable can be accessed only
with in that class.
Public:
Protected:
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
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.
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
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
called finalization. By using finalization, you can define specific actions that will occur
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
periodically, checking for objects that are no longer referenced by any running
freed, the Java run time calls the finalize( ) method on the object.
}
Änheritance:
Sub class
B
B C D
B D
// Create a superclass.
class A
{
int i, j;
void showij()
{
}
// Create a subclass by extending class A.
class B extends A
{
int k;
void showk()
{
void sum()
{
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance
{
subOb.i = ;
subOb.j = 8;
subOb.k = 9;
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()
{
}
}
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:
the superclass of the su class in which it is used. his usage has the following
general form:
super.mem er
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;
class B extends A
{
B(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}
void show()
{
}
}
class seSuper
{
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
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
class A {
A()
{
System.out.println("Inside A's constructor.");
}
class B extends A {
B() {
System.out.println("Inside B's constructor.");
}
}
// Create another subclass by extending B.
class C extends B
{
C() {
class CallingCons
{
public static void main(String args[ ])
{
C c = new C();
}
}
The output from this program is shown here:
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.
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;
super(a, b);
k = c;
}
// display k ± this overrides show() in A
void show() {
System.out.println("k: " + k);
}
}
class Override {
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);
}
double area()
{
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:
4inal method:
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
{
}
class staticdemo
{
}
output:
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;
obj1.printval();
}
}
Output:
There are situations in which you will want to define a super class that declares the
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
determines the nature of the methods that the subclasses must implement.
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
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()
{
}
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 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 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.
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();
}
base class.
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
The main reason for using packages is to guarantee the uniqueness of class names
Employee class.
As long as both of them place their class into different packages, then there is no
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:
For example, you can import all classes in the java.util package with the statement:
import java.util.*;
import java.util.Date;
ser defined packages:
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
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>
Errors :
1. Syntax (occur at compile time)
2. Logical (errors occur at runtime)
Exception handling:
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
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 {
}
finally {
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 {
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.");
}
}
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
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
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[ ] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e) {
a=0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
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
class NestTry {
try {
int a = args.length;
int b = 42 / a;
if(a==1) a = a/(a-a);
// division by zero
int c[ ] = { 1 };
using the throw statement. The general form of throw is shown here:
throw ThrowableInstance;
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:
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
All other exceptions that a method can throw must be declared in the throws clause. If
// body of method
}
Example:
class ThrowsDemo {
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.
occurring Of the exception and end of the blocked will be skipped and the
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");
}
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
multitasking
julti hreading:
by virtually all modern operating systems. However, there are two distinct types
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.
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
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
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
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
Java¶s multithreading system is built upon the Thread class, its methods, and its
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
In the most general sense, you create a thread by instantiating an object of type Thread.
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[ ])
{
Thread.sleep(1000);
}
}
catch (InterruptedException e)
}
}
following statement:
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
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
super("Demo Thread");
}
// This is the entry point for the second thread.
Thread.sleep(500);
} catch (InterruptedException e)
{
System.out.println("Child interrupted.");
}
new NewThread();
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
derived fromThread . Notice the call to super( ) inside NewThread . This invokes
Thread t;
NewThread(String threadname)
{
name = threadname;
try {
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");
}
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
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:
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:
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
Thread t;
NewThread(String threadname)
{
name = threadname;
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");
ob2.t.join();
ob3.t.join();
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
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.
Here, level specifies the new priority setting for the calling thread.
within Thread
You can obtain the current priority setting by calling the getPriority( ) method of
public clicker(int p)
{
t = new Thread(this);
t.setPriority(p);
}
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();
Try
{
hi.t.join();
lo.t.join();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Low-priority thread: " + lo.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
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
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
The third version creates a label that contains the string specified by
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
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));
}
}
class mylabel
{
public static void main(String args[])
{
myf obj=new myf();
}
}
Java mylabel
sing Buttons:
The most widely used control is the push button. A 0is 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:
Checkbox( )
Checkbox(String )
of the check box is unchecked. The second form creates a check box
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
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
boolean getState( )
String getLabel( )
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:
" 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
TextField( )
TextField(int )
TextField(String )
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
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 .
String getText( )
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(String )
specified by In the fifth form you can specify the scroll bars that
SCROLLBARS_BOTH SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY
SCROLLBARS_VERTICAL_ONLY
Applet:
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
. 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
displayed onscreen. So, if a user leaves a web page and comes back, the
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
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
The stopr method is called when a web browser leaves the HTML
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
you should free up any resources the applet may be using. The stopr
The above code must be inserted to execute the applet or u can use
<BODY>
</BODY>
</HTML>
Drawing Lines:
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:
// 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:
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:
By default, graphics objects are drawn in the current foreground color. You
can change this color by calling the Graphics method setColorr :
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
g.setColor(c2);
g.setColor(c3);
g.setColor(Color.blue);
g.setColor(Color.cyan);
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:
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
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 .)
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:
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
BorderLayout( )
BorderLayout.CENTER BorderLayout.SOTH
BorderLayout.EAST BorderLayout.WEST
BorderLayout.NORTH
When adding components, you will use these constants with the following form of
Here,
80$is the component to be added, and specifies where the
component will be added.
GridLayout:
GridLayout( )
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( )
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:
Here, is a string that specifies the name of the card whose panel
is specified by 80$.