Java
Java
A
What is java?
• Based on C/C++
• Secure
– usage in networked environments requires more security
– memory allocation model is a major defense
– access restrictions are forced (private, public)
Java Features (4)
• Multithreaded
– 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
javac HelloWorldApp.java
it generates a file named HelloWorldApp.class
boolean expressions,
logical OR
they are also called |
Boolean Operators. ||
condition OR
Circle
centre
radius
circumference()
area()
Classes
• A class is a collection of fields (data) and methods
(procedure or function) that operate on that data.
• The basic syntax for a class definition:
class ClassName [extends
SuperClassName]
{
[fields declaration]
[methods declaration]
• Bare bone class
} – no fields, no methods
type MethodName
(parameter-list)
{
Method-body;
}
Adding Methods to Class Circle
public class Circle {
Circle aCircle;
Circle bCircle;
Class of Circle cont.
• aCircle, bCircle simply refers to a Circle
object, not an object itself.
aCircle bCircle
null null
bCircle = aCircle;
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;
bCircle = aCircle;
Before Before
Assignment Assignment
aCircl bCircl aCircl bCircl
e e e e
P Q P Q
Automatic garbage collection
• The object Q does not have a
reference and cannot be used in future.
ObjectName.VariableName
ObjectName.MethodName(parameter-list)
double area;
aCircle.r = 1.0;
area = aCircle.area();
Using 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=78.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:
X=23;
Y=94; obj
}
}
class Val
{
Public static void main(String args[ ])
{
Rectangle obj=new Rectangle( );
}
}
Polymorphism:
Method overloading:
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 {
...
}
}
Terminology: 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.
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
Private:
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
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 finalize( ) 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.
}
Inheritance:
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 = 7;
subOb.j = 8;
subOb.k = 9;
Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24
The 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 subclass in which it is used. This usage has the following
general form:
super.member
of a subclass hide members by the same name in the superclass. Consider this simpleclass hierarchy:
// Using 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 UseSuper
{
subOb.show();
}
}
This program displays the following:
i in superclass: 1
i in subclass: 2
When Constructors Are 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
override the method in the superclass. When an overridden method is called from
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;
}
}
class FindAreas
{
public static void main(String args[])
{
Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref;
figref = r;
Final method:
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 :
EX:
Final int PASS_MARK = 40;
Static Method:
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 keyword at the beginning of the class declaration. There 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 :
An interface is very much like a class with constant values and method
declarations
The methods in an interface are directly are only declared but not
implemented
Implicitly all the methods in an interface are abstract
Implicitly 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.
All the methods and variables are implictly public with their interface itself
is declared as public.
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
Using 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;
User 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.
✔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
{
System.out.println("procB's finally");
}
Output:
inside procA
procA's finally
Exception caught
inside procB
procB's finally
inside procC
procC's finally
Multi Threading:
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
Multi Threading:
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 CPU, 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
CPU. 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 CPU is sitting idle most of the
time. Multithreading lets you gain access to this idle time and put it to good use
The Java Thread Model:
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
runnabl notify, notifyAll,
new
e IO complete,
sleep expired,
yield,
scheduler join complete
time
slice
running blocked
IO, 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 CPU 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
Extending Thread:
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 CPU. 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.
Thread 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 str)
Label(String str, int how)
The first version creates a blank label. The second version creates a
label that contains the string specified by str. This string is left-justified.
The third version creates a label that contains the string specified by str
using the alignment specified by how. The value of how must be one of
For setText( ), str specifies the new label. For getText( ), 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();
}
}
Javac mylabel.java
Java mylabel
Using Buttons:
The most widely used control is the push button. A push button is a component
that contains a label and that generates an event when it is pressed. Push
buttons are objects of type Button. Button defines these two constructors:
Button( )
Button(String str)
The first version creates an empty button. The second creates a button that
contains str as a label.
After a button has been created, you can set its label by calling
setLabel( ). You can retrieve its label by calling getLabel( ). These methods
are as follows:
Checkbox( )
Checkbox(String str)
of the check box is unchecked. The second form creates a check box
whose label is specified by str. The state of the check box is unchecked.
The third form allows you to set the initial state of the check box. If on 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 str and
group, then cbGroup must be null. (Check box groups are described in the
next section.) The value of on determines the initial state of the check box.
To retrieve the current state of a check box, call getState( ). To set its
state, call setState( ). You can obtain the current label associated with a
boolean getState( )
String getLabel( )
edit control.Text fields allow the user to enter strings and to edit the text using
the arrow keys, cut and paste keys, and mouse selections. TextField is a
TextField( )
TextField(int numChars)
TextField(String str)
field that is numChars characters wide. The third form initializes the text field
with the string contained in str. 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 getText( ). To set the text, call setText( ).
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 TextArea. Following are
the constructors for TextArea:
TextArea( )
TextArea(String str)
specified by str. In the fifth form you can specify the scroll bars that
you want the control to have. sBars must be one of these values:
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
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )
init( )
The init( ) 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 start( ) method is called after init( ). It is also called to restart an applet
after it has been stopped. Whereas init( ) is called once—the first time an
displayed onscreen. So, if a user leaves a web page and comes back, the
The paint( ) 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. paint( ) is also called
when the applet begins execution. Whatever the cause, whenever the applet must
redraw its output, paint( ) is called. The paint( ) 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 stop( ) method is called when a web browser leaves the HTML
should use stop( ) to suspend threads that don’t need to run when the
applet is not visible. You can restart them when start( ) is called if the
you should free up any resources the applet may be using. The stop( )
The above code must be inserted to execute the applet or u can use
<BODY>
</BODY>
</HTML>
Drawing Lines:
void drawRoundRect(int top, int left, int width, int height,int xDiam, int yDiam)
void fillRoundRect(int top, int left, int width, int height,int xDiam, int yDiam)
// 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(70, 90, 140, 100, 30, 40);
}
}
Drawing Ellipses and Circles
// 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, 75, 50);
g.drawOval(190, 10, 90, 30);
g.fillOval(70, 90, 140, 100);
}
}
Drawing Arcs:
void drawArc(int top, int left, int width, int height, int startAngle,int sweepAngle)
void fillArc(int top, int left, int width, int height, int startAngle,int sweepAngle)
// 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, 70, 70, 0, 75);
g.fillArc(100, 40, 70, 70, 0, 75);
g.drawArc(10, 100, 70, 80, 0, 175);
g.fillArc(100, 100, 70, 90, 0, 270);
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 setColor( ):
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 LayoutManager
interface. The layout manager is set by the setLayout( ) method. If no call
to setLayout( ) 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
setLayout( ) method has the following general form:
Here, layoutObj is a reference to the desired layout manager. If you wish to disable
the layout manager and position components manually, pass null for layoutObj. If
you do this, you will need to determine the shape and position of each component
FlowLayout is the default layout manager. This is the layout manager that
the preceding examples have used. FlowLayout 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 FlowLayout:
FlowLayout( )
FlowLayout(int how)
leaves five pixels of space between each component. The second form lets
you specify how each line is aligned. Valid values for how 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
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.SOUTH
BorderLayout.EAST BorderLayout.WEST
BorderLayout.NORTH
When adding components, you will use these constants with the following form of
Here, compObj is the component to be added, and region 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 horz and vert, respectively. Either numRows or
numColumns can be zero. Specifying numRows as zero allows for
unlimited-length columns. Specifying numColumns 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 add( ) when adding
cards to a panel:
Here, name is a string that specifies the name of the card whose panel
is specified by panelObj.