You are on page 1of 51

interface abstract "class" that is used to group related methods with "empty" bodies

Interface looks like a class but it is not a class.


FEATURES:VMOI

An interface can have methods and variables just like the class but the methods declared in
interface are by default abstract (only method signature, no body).

Also, the variables declared in an interface are public, static & final by default.

The class that implements interface must implement all the methods of that interface.

We can’t instantiate an interface in java. That means we cannot create the object of an
interface.

Also, java programming language does not allow you to extend more than one class,
However you can implement more than one interfaces in your class.
interface MyInterface class Demo implements MyInterface
{ {
/* This class must have to implement both the abstract
/* compiler will treat them as: methods
* else you will get compilation error
* public abstract void method1(); */
public void method1()
* public abstract void method2(); {
*/ System.out.println("implementation of method1");
}
public void method1(); public void method2()
{
public void method2(); System.out.println("implementation of method2");
} }
public static void main(String arg[])
{
MyInterface obj = new Demo();
obj.method1();
}
}
interface Inf1{
public void method1();
}
interface Inf2 extends Inf1 {
public void method2();
}
public class Demo implements Inf2{
/* Even though this class is only implementing the
* interface Inf2, it has to implement all the methods
* of Inf1 as well because the interface Inf2 extends Inf1
*/
public void method1(){
System.out.println("method1");
}
public void method2(){
System.out.println("method2");
}
public static void main(String args[]){
Inf2 obj = new Demo();
obj.method2();
}
}
Interface variables must be initialized at Inside any implementation class, you
the time of declaration otherwise cannot change the variables declared in
compiler will throw an error. interface because by default, they are
public, static and final.

class Sample implements Try


interface Try
{
{ public static void main(String args[])
int a=10; {
public int a=10; a=20; //compile time error
}
public static final int a=10;
}
final int a=10;
static int a=0;
}

All of the above statements are identical.


While providing implementation in class of any method of an interface, it needs
to be mentioned as public.

All the interface methods are by default abstract and public.

Class that implements any interface must implement all the methods of that
interface, else the class should be declared abstract.
Packages in java
A package as the name suggests is a pack(group) of classes, interfaces and other
packages.

In java we use packages to organize our classes and interfaces. We have two types of
packages in Java: built-in packages and the packages we can create (also known as
user defined package).

In java we have several built-in packages, when we need a pacakge, we import a


package like this:

import java.util.Scanner what is


types of package:eg
Here: advantages of packagrs
→ java is a top level package eg
→ util is a sub package
→ and Scanner is a class which is present in the sub package util.
These are the reasons why you should use packages in Java:
RON
Reusability: While developing a project in java, we often feel that there are few
things that we are writing again and again in our code. Using packages, you can
create such things in form of classes inside a package and whenever you need to
perform that same task, just import that package and use the class.

Better Organization: Again, in large java projects where we have several hundreds
of classes, it is always required to group the similar types of classes in a
meaningful package name so that you can organize your project better and when
you need something you can quickly locate it and use it, which improves the
efficiency.

Name Conflicts: We can define two classes with the same name in different
packages so to avoid name collision, we can use packages
You can create a class Calculator inside a package name letmecalculate.

To create a class inside a package, declare the package name in the first statement in your
program. A class can have only one package declaration.
Calculator.java file created inside a package letmecalculate

package letmecalculate;

public class Calculator {


public int add(int a, int b){
return a+b;
}
public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(10, 20));
}
}
Sub packages in Java
A package inside another package is known as sub package. For example If I create a package
inside letmecalculate package then that will be called sub package.

Lets say I have created another package inside letmecalculate and the sub package name is
multiply. So if I create a class in this subpackage it should have this package declaration in the
beginning:

package letmecalculate.multiply;
public class Multiplication {
int product(int a, int b){
return a*b;
}
}
Now if I need to use this Multiplication class I have to either import the package like this:

import letmecalculate.multiply;
Exception handling in java
An Exception is an unwanted event that interrupts the normal flow of the
program.

When an exception occurs program execution gets terminated. In such cases


we get a system generated error message.

The good thing about exceptions is that they can be handled in Java. By
handling the exceptions we can provide a meaningful message to the user
about the issue rather than a system generated message, which may not be
understandable to a user.

There can be several reasons that can cause a program to throw exception.
For example: Opening a non-existing file in your program, Network
connection problem, bad input data provided by user etc.
Types of exceptions
There are two types of exceptions in Java:
1)Checked exceptions
2)Unchecked exceptions

Checked exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions as the
compiler checks them during compilation to see whether the programmer has handled
them or not. If these exceptions are not handled/declared in the program, you will get
compilation error. For example, SQLException, IOException, ClassNotFoundException
etc.

Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not
checked at compile-time so compiler does not check whether the programmer has
handled them or not but it’s the responsibility of the programmer to handle these
exceptions and provide a safe exit. For example, ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException etc.
Java handles exceptions by using following keywords:
try
catch
finally block
Throw and
throws clause
Try block Catch block
A catch block is where you handle the exceptions, this
The try block contains set of block must follow the try block. A single try block can
statements where an exception can have several catch blocks associated with it. You can
occur. A try block is always followed catch different exceptions in different catch blocks.
by a catch block, which handles the When an exception occurs in try block, the
corresponding catch block that handles that particular
exception. exception executes. For example if an arithmetic
A try block must be followed by catch exception occurs in try block then the statements
enclosed in catch block for arithmetic exception
blocks or finally block or both. executes.

Syntax of try catch in java


Syntax of try block try
{
try{ //statements that may cause an exception
//statements that may cause an }
catch (exception(type) e(object))
exception {
} //error handling code
}
class Example1 {
catch (ArithmeticException e) {
public static void main(String
System.out.println("You should not divide a
args[]) { number by zero");
int num1, num2; }
try { catch (Exception e) {
System.out.println("Exception occurred");
num1 = 0; }
num2 = 62 / num1; System.out.println("I'm out of try-catch
block in Java.");
System.out.println(num2); }
System.out.println("Hey I'm at }
the end of try block"); Output:
}
You should not divide a number by zero
I'm out of try-catch block in Java.
A finally block contains all the crucial statements that must be executed
whether exception occurs or not.
The statements present in this block will always execute regardless of
whether exception occurs in try block or not such as closing a connection,
stream etc.

Output:
class Example
{ Number should not be divided by zero
public static void main(String args[]) { This is finally block
try{ Out of try-catch-finally
int num=121/0;
System.out.println(num);
}
catch(ArithmeticException e){
System.out.println("Number should not be divided by zero");
}
finally{
System.out.println("This is finally block");
}
System.out.println("Out of try-catch-finally");
} }
The throws does the same thing that try-catch But suppose you have several such methods that can
does but there are some cases where you would cause exceptions, in that case it would be tedious to
prefer throws over try-catch. For example:
write these try-catch for each method. The code will
Lets say we have a method myMethod() that has
statements that can throw either become unnecessary long and will be less-readable.
ArithmeticException or NullPointerException, in
this case you can use try-catch as shown below: One way to overcome this problem is by using throws
like this: declare the exceptions in the method signature
public void myMethod() using throws and handle the exceptions where you are
{ calling this method by using try-catch.
try {
// Statements that might throw an exception Another advantage of using this approach is that you will
} be forced to handle the exception when you call this
catch (ArithmeticException e) { method, all the exceptions that are declared using
// Exception handling statements throws, must be handled where you are calling this
method else you will get compilation error.
}
catch (NullPointerException e) {
// Exception handling statements
}
}
import java.io.*;
public void myMethod() throws ArithmeticException, NullPointerException
class ThrowExample {
{
void myMethod(int num)throws IOException,
// Statements that might throw an exception
ClassNotFoundException{
}
if(num==1)
public static void main(String args[]) {
throw new IOException("IOException Occurred");
try {
else
myMethod();
throw new
} ClassNotFoundException("ClassNotFoundException");
catch (ArithmeticException e) { }
// Exception handling statements }
}
catch (NullPointerException e) { public class Example1{
// Exception handling statements public static void main(String args[]){
} try{
} ThrowExample obj=new ThrowExample();
obj.myMethod(1);
}catch(Exception ex){
System.out.println(ex);
}
}}
Output:

java.io.IOException: IOException Occurred


String
String is a sequence of characters, for e.g. “Hello” is a string of 5 characters. In java, string is an immutable
object which means it is constant and can cannot be changed once it has been created.
There are two ways to create a String in Java

String literal
Using new keyword

String literal
In java, Strings can be created like this: Assigning a String literal to a String instance:

String str1 = "Welcome";


String str2 = "Welcome";

We can create strings using new:

String str1 = new String("Welcome");


String str2 = new String("Welcome");
Java String Methods
Here are the list of the methods available in the Java String class.

char charAt(int index): It returns the character at the specified index. Specified index value should be between 0 to length() -1 both inclusive.

boolean equals(Object obj): Compares the string with the specified string and returns true if both matches else false.

boolean equalsIgnoreCase(String string): It works same as equals method but it doesn’t consider the case while comparing strings. It does a case
insensitive comparison.

int compareTo(String string): This method compares the two strings based on the Unicode value of each character in the strings.

int compareToIgnoreCase(String string): Same as CompareTo method however it ignores the case during comparison.

boolean startsWith(String prefix, int offset): It checks whether the substring (starting from the specified offset index) is having the specified prefix or
not.

boolean startsWith(String prefix): It tests whether the string is having specified prefix, if yes then it returns true else false.

boolean endsWith(String suffix): Checks whether the string ends with the specified suffix.

int hashCode(): It returns the hash code of the string.


int indexOf(int ch): Returns the index of first occurrence of the specified character ch in the string.

int indexOf(int ch, int fromIndex): Same as indexOf method however it starts searching in the string from the specified
fromIndex..

int lastIndexOf(int ch): It returns the last occurrence of the character ch in the string.

int lastIndexOf(int ch, int fromIndex): Same as lastIndexOf(int ch) method, it starts search from fromIndex.

int indexOf(String str): This method returns the index of first occurrence of specified substring str.

int lastindexOf(String str): Returns the index of last occurrence of string str.

String substring(int beginIndex): It returns the substring of the string. The substring starts with the character at the
specified index.

String substring(int beginIndex, int endIndex): Returns the substring. The substring starts with character at beginIndex and
ends with the character at endIndex.

String concat(String str): Concatenates the specified string “str” at the end of the string.

String replace(char oldChar, char newChar): It returns the new updated string after changing all the occurrences of oldChar
with the newChar.
String toUpperCase(): Equivalent to toUpperCase(Locale.getDefault()).

public String intern(): This method searches the specified string in the memory pool and if it is found then it
returns the reference of it, else it allocates the memory space to the specified string and assign the reference to it.

public boolean isEmpty(): This method returns true if the given string has 0 length. If the length of the specified
Java String is non-zero then it returns false.

public static String join(): This method joins the given strings using the specified delimiter and returns the
concatenated Java String

String replaceFirst(String regex, String replacement): It replaces the first occurrence of substring that fits the given
regular expression “regex” with the specified replacement string.

String replaceAll(String regex, String replacement): It replaces all the occurrences of substrings that fits the regular
expression regex with the replacement string.

String[] split(String regex, int limit): It splits the string and returns the array of substrings that matches the given
regular expression. limit is a result threshold here.

String[] split(String regex): Same as split(String regex, int limit) method however it does not have any threshold
limit.
String toLowerCase(Locale locale): It converts the string to lower case string using the rules defined by given
locale.

public static String format(): This method returns a formatted java String

String toLowerCase(): Equivalent to toLowerCase(Locale. getDefault()).

String trim(): Returns the substring after omitting leading and trailing white spaces from the original string.

char[] toCharArray(): Converts the string to a character array.

static String copyValueOf(char[] data): It returns a string that contains the characters of the specified character
array.

static String copyValueOf(char[] data, int offset, int count): Same as above method with two extra arguments –
initial offset of subarray and length of subarray.

void getChars(int srcBegin, int srcEnd, char[] dest, int destBegin): It copies the characters of src array to the dest
array. Only the specified range is being copied(srcBegin to srcEnd) to the dest subarray(starting fromdestBegin).
static String valueOf(): This method returns a string representation of passed arguments such as int, long, float, double, char and char array.

boolean contentEquals(StringBuffer sb): It compares the string to the specified string buffer.

boolean regionMatches(int srcoffset, String dest, int destoffset, int len): It compares the substring of input to the substring of specified string.

boolean regionMatches(boolean ignoreCase, int srcoffset, String dest, int destoffset, int len): Another variation of regionMatches method with the
extra boolean argument to specify whether the comparison is case sensitive or case insensitive.

byte[] getBytes(String charsetName): It converts the String into sequence of bytes using the specified charset encoding and returns the array of
resulted bytes.

byte[] getBytes(): This method is similar to the above method it just uses the default charset encoding for converting the string into sequence of bytes.

int length(): It returns the length of a String.

boolean matches(String regex): It checks whether the String is matching with the specified regular expression regex.

int codePointAt(int index):It is similar to the charAt method however it returns the Unicode code point value of specified index rather than the
character itself.

boolean contains(CharSequence s): It checks whether the string contains the specified sequence of char values. If yes then it returns true else false. It
throws NullPointerException of ‘s’ is null.

String toUpperCase(Locale locale): Converts the string to upper case string using the rules defined by specified locale.
Multithreading in java
A thread is a light-weight smallest part of a process that can run concurrently
with the other parts(other threads) of the same process.

Threads are independent because they all have separate path of execution
that’s the reason if an exception occurs in one thread, it doesn’t affect the
execution of other threads. All threads of a process share the common memory.

The process of executing multiple threads simultaneously is known as


multithreading.
Thread Life Cycle
New: Whenever a new thread is
created, it is always in the new state.
For a thread in the new state, the
code has not been run yet and thus
has not begun its execution.

Active: When a thread invokes the


start() method, it moves from the new
state to the active state. The active
state contains two states within it:
one is runnable, and the other is
running.

Runnable: A thread, that is ready to


run is then moved to the runnable
state. In the runnable state, the
thread may be running or may be
ready to run at any given instant of
time. It is the duty of the thread
scheduler to provide the thread time
to run, i.e., moving the thread the
running state.
A program implementing multithreading acquires a fixed slice of time to each individual
thread. Each and every thread runs for a short span of time and when that allocated time slice
is over, the thread voluntarily gives up the CPU to the other thread, so that the other threads
can also run for their slice of time. Whenever such a scenario occurs, all those threads that are
willing to run, waiting for their turn to run, lie in the runnable state. In the runnable state,
there is a queue where the threads lie.

Running: When the thread gets the CPU, it moves from the runnable to the running state.
Generally, the most common change in the state of a thread is from runnable to running and
again back to runnable.
Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently) then,
either the thread is in the blocked state or is in the waiting state.

For example, a thread (let's say its name is A) may want to print some data from the printer.
However, at the same time, the other thread (let's say its name is B) is using the printer to print
some data. Therefore, thread A has to wait for thread B to use the printer. Thus, thread A is in
the blocked state. A thread in the blocked state is unable to perform any execution. If there are
a lot of threads in the waiting or blocked state, then it is the duty of the thread scheduler to
determine which thread to choose and which one to reject, and the chosen thread is then
given the opportunity to run.
Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its
name is A) has entered the critical section of a code and is not willing to leave that
critical section. In such a scenario, another thread (its name is B) has to wait forever,
which leads to starvation. To avoid such scenario, a timed waiting state is given to
thread B. Thus, thread lies in the waiting state for a specific span of time, and not
forever. A real example of timed waiting is when we invoke the sleep() method on a
specific thread. The sleep() method puts the thread in the timed wait state. After the
time runs out, the thread wakes up and start its execution from when it has left
earlier.

Terminated: A thread reaches the termination state because of the following reasons:

When a thread has finished its job, then it exists or terminates normally.
Abnormal termination: It occurs when some unusual events such as an unhandled
exception or segmentation fault.
A terminated thread means the thread is no more in the system. In other words, the
thread is dead, and there is no way one can respawn (active after kill) the dead
thread.
Creating a thread in Java
There are two ways to create a thread in Java:
1) By extending Thread class.
2) By implementing Runnable interface.

Few methods of Thread class

getName(): It is used for Obtaining 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
class MultithreadingDemo implements Runnable{
public void run(){
System.out.println("My thread is in running state.");
class MultithreadingDemo extends
Thread{ }
public static void main(String args[]){
public void run(){ MultithreadingDemo obj=new MultithreadingDemo();
System.out.println("My thread is in Thread tobj =new Thread(obj);
running state."); tobj.start();
} }
public static void main(String args[]){ }
Output:
MultithreadingDemo obj=new
MultithreadingDemo(); My thread is in running state.
obj.start();
}
}
Output:

My thread is in running state.


class Count implements Runnable {
Thread mythread ; Output:
Count() {
mythread = new Thread(this, "my runnable thread"); my thread createdThread[my runnable
System.out.println("my thread created" + mythread); thread,5,main]
mythread.start(); } Main thread will be alive till the child thread is live
public void run() { Printing the count 0
try { Printing the count 1
for (int i=0 ;i<10;i++) { Main thread will be alive till the child thread is live
System.out.println("Printing the count " + i);
Printing the count 2
Thread.sleep(1000); } }
Main thread will be alive till the child thread is live
Printing the count 3
catch(InterruptedException e) {
Printing the count 4
System.out.println("my thread interrupted"); }
Main thread will be alive till the child thread is live
System.out.println("mythread run is over" ); }}
Printing the count 5
class RunnableExample {
Main thread will be alive till the child thread is live
public static void main(String args[])
Printing the count 6
{ Count cnt = new Count(); Printing the count 7
try { Main thread will be alive till the child thread is live
while(cnt.mythread.isAlive()) { Printing the count 8
System.out.println("Main thread will be alive till the child thread is live"); Main thread will be alive till the child thread is live
Thread.sleep(1500); } } Printing the count 9
catch(InterruptedException e) { mythread run is over
System.out.println("Main thread interrupted"); } Main thread run is over
System.out.println("Main thread run is over" ); }}
Thread priorities
Thread priorities are the integers which decide how one thread should be treated with respect to the others.
Thread priority decides when to switch from one running thread to another, process is called context switching
A thread can voluntarily release control and the highest priority thread that is ready to run is given the CPU.
A thread can be preempted by a higher priority thread no matter what the lower priority thread is doing.
Whenever a higher priority thread wants to run it does.
To set the priority of the thread setPriority() method is used which is a method of the class Thread Class.
In place of defining the priority in integers, we can use MIN_PRIORITY, NORM_PRIORITY or MAX_PRIORITY.

Methods: isAlive() and join()


In all the practical situations main thread should finish last else other threads which have spawned from the main
thread will also finish.
To know whether the thread has finished we can call isAlive() on the thread which returns true if the thread is
not finished.
Another way to achieve this by using join() method, this method when called from the parent thread makes
parent thread wait till child thread terminates.
These methods are defined in the Thread class.
We have used isAlive() method in the above examples too.
Synchronization
Multithreading introduces asynchronous behavior to the programs. If a
thread is writing some data another thread may be reading the same data
at that time. This may bring inconsistency.

When two or more threads need access to a shared resource there should
be some way that the resource will be used only by one resource at a time.
The process to achieve this is called synchronization.

To implement the synchronous behavior java has synchronous method.


Once a thread is inside a synchronized method, no other thread can call any
other synchronized method on the same object. All the other threads then
wait until the first thread come out of the synchronized block.
Inter-thread Communication
We have few methods through which java threads can communicate with each
other. These methods are wait(), notify(), notifyAll(). All these methods can only
be called from within a synchronized method.

1) To understand synchronization java has a concept of monitor. Monitor can be


thought of as a box which can hold only one thread. Once a thread enters
the monitor all the other threads have to wait until that thread exits the
monitor.

2) wait() tells the calling thread to give up the monitor and go to sleep until
some other thread enters the same monitor and calls notify().

3) notify() wakes up the first thread that called wait() on the same object.
notifyAll() wakes up all the threads that called wait() on the same object. The
highest priority thread will run first.
public class JoinExample {
class MyClass implements Runnable{
public static void main(String[] args) {
Thread th1 = new Thread(new MyClass(), "th1"); @Override
Thread th2 = new Thread(new MyClass(), "th2"); public void run() {
Thread th3 = new Thread(new MyClass(), "th3"); Thread t = Thread.currentThread();
// Start first thread immediately System.out.println("Thread started: "+t.getName());
th1.start(); try {
/* Start second thread(th2) once first thread(th1) is dead */ Thread.sleep(4000);
try { th1.join(); } } catch (InterruptedException ie) {
catch (InterruptedException ie) {
ie.printStackTrace();
}
ie.printStackTrace(); }
System.out.println("Thread ended: "+t.getName());
th2.start();
/* Start third thread(th3) once second thread(th2) * is dead */
}
try { th2.join(); }
} catch (InterruptedException ie) { ie.printStackTrace(); Output:
}
th3.start(); Thread started: th1
// Displaying a message once third thread is dead Thread ended: th1
try { th3.join(); Thread started: th2
} catch (InterruptedException ie) { Thread ended: th2
ie.printStackTrace(); }
Thread started: th3
Thread ended: th3
System.out.println("All three threads have finished execution");
All three threads have finished execution
}
}
Java AWT https://www.youtube.com/watch?v=QEMBucYSi9s+notes from this only

AWT stands for Abstract Window Toolkit. It is a platform dependent API for creating
Graphical User Interface (GUI) for java programs.

Java AWT calls native platform (Operating systems) subroutine for creating
components such as textbox, checkbox, button etc.

For example an AWT GUI having a button would have a different look and feel across
platforms like windows, Mac OS & Unix, this is because these platforms have different
look and feel for their native buttons and AWT directly calls their native subroutine
that creates the button.

AWT components are considered heavy weight because they are being generated by
underlying operating system (OS). For example if you are instantiating a text box in
AWT that means you are actually asking OS to create a text box for you.
AWT hierarchy
Components and containers
All the elements like buttons, text fields, scrollbars etc are known as
components.

In AWT we have classes for each component as shown in the above diagram. To
have everything placed on a screen to a particular position, we have to add
them to a container.

A container is like a screen wherein we are placing components like buttons,


text fields, checkbox etc. In short a container contains and controls the layout of
components.

A container itself is a component (shown in the above hierarchy diagram) thus


we can add a container inside container.
Types of containers:

As explained above, a container is a place wherein we add components like text field,
button, checkbox etc. There are four types of containers available in AWT: Window,
Frame, Dialog and Panel.

Window: An instance of the Window class has no border and no title

Dialog: Dialog class has border and title. An instance of the Dialog class cannot exist
without an associated instance of the Frame class.

Panel: Panel does not contain title bar, menu bar or border. It is a generic container for
holding components. An instance of the Panel class provides a container to which to
add components.

Frame: A frame has title, border and menu bars. It can contain several components like
buttons, text fields, scrollbars etc. This is most widely used container while developing
an application in AWT.
We can create a GUI using Frame in two ways:
1) By extending Frame class
2) By creating the instance of Frame class
Lets have a look at the example of each one.
import java.awt.*;
public class SimpleExample extends Frame{
SimpleExample(){
Button b=new Button("Button!!");
// setting button position on screen
b.setBounds(50,50,50,50);
//adding button into frame
add(b);
//Setting Frame width and height
setSize(500,300);
//Setting the title of Frame
setTitle("This is my First AWT example");
//Setting the layout for the Frame
setLayout(new FlowLayout());
/* By default frame is not visible so we are setting the visibility
to true to make it visible. */
setVisible(true);
}
public static void main(String args[]){
// Creating the instance of Frame
SimpleExample fr=new SimpleExample();
}}
import java.awt.*;
public class Example2 {
Example2()
{
//Creating Frame
Frame fr=new Frame();
//Creating a label
Label lb = new Label("UserId: ");
//adding label to the frame
fr.add(lb);
//Creating Text Field
TextField t = new TextField();
//adding text field to the frame
fr.add(t);
//setting frame size
fr.setSize(500, 300);
//Setting the layout for the Frame
fr.setLayout(new FlowLayout());
fr.setVisible(true);
}
public static void main(String args[])
{
Example2 ex = new Example2();
}}
Event and Listener (Java Event Handling)
Changing the state of an object is known as an event.
Event handling has three main components,
• Events: An event is a change in state of an object.

• Events Source: An event source is an object that generates an event.

• Listeners: A listener is an object that listens to the event. A listener gets


notified when an event occurs.

A source produces an event and sends it with the source to one or more
listeners. Once the listener receives the event, the event will be processed and
returned. Many Java packages, such as java.util, java.awt and java.awt.event,
support events.
Delegation event model
The modern approach to handling events is based
on the delegation event model, which defines
standard and consistent mechanisms to generate
and process events. Its concept is quite simple: a
source generates an event and sends it to one or
more listeners.

In this scheme, the listener simply waits until it


receives an event. Once an event is received, the
listener processes the event and then returns. The A user interface element is able to “delegate” the processing of
advantage of this design is that the application logic an event to a separate piece of code.
that processes events is cleanly separated from the
user interface logic that generates those events. In the delegation event model, listeners must register with a
source in order to receive an event notification.

This provides an important benefit: notifications are sent only


to listeners that want to receive them.

This is a more efficient way to handle events than the design


used
by the original Java 1.0 approach.
Event Classes and Interface AMKIT+WFC
(AMIT WITH A K (JOH WF AUR CHUTIYAA BOLTA RHTA
HAI)

Event Classes Description Listener Interface


generated when button is pressed, menu-item is
ActionEvent ActionListener
selected, list-item is double clicked
generated when mouse is dragged,
MouseEvent moved,clicked,pressed or released and also when it MouseListener
enters or exits a component
KeyEvent generated when input is received from keyboard KeyListener
ItemEvent generated when check-box or list item is clicked ItemListener
generated when value of textarea or textfield is
TextEvent TextListener
changed
MouseWheelEvent generated when mouse wheel is moved MouseWheelListener
generated when window is activated, deactivated,
WindowEvent WindowListener
deiconified, iconified, opened or closed
generated when component is hidden, moved, resized
ComponentEvent ComponentEventListener
or set visible
generated when component is added or removed
ContainerEvent ContainerListener
from container
AdjustmentEvent generated when scroll bar is manipulated AdjustmentListener
generated when component gains or loses keyboard
FocusEvent FocusListener
focus
Steps to handle events: public void keyReleased(KeyEvent k)
{
Implement appropriate interface in showStatus("KeyRealesed");
the class. }
public void keyTyped(KeyEvent k)
Register the component with the {
listener. msg = msg+k.getKeyChar();
import java.awt.*; repaint();
import java.awt.event.*; }
import java.applet.*; public void paint(Graphics g)
public class Test extends Applet implements KeyListener {
{ g.drawString(msg, 20, 40);
String msg=""; }
public void init() }
{ HTML code:
addKeyListener(this); <applet code="Test" width=300, height=100>
} </applet>
public void keyPressed(KeyEvent k)
{
showStatus("KeyPressed");
}
Java Applet
Applet is a Java program that can be transported over the internet and
executed by a Java-enabled web-browser(if a browser is supporting the
applets) or an applet can be executed using the appletviewer utility provided
with JDK.

Applet is embedded in the webpage to generate the dynamic content. It runs


inside the browser and works at client side.

An applet is created by using the Applet class, which is a part


of java.applet package. Applet class provides several useful methods to give
you full control over the execution of an applet.
The lifecycle of an applet
through its methods-

Lifecycle of Java Applet


• Applet is initialized.
• Applet is started.
• Applet is painted.
• Applet is stopped.
• Applet is destroyed.
public void init(): is used to initialized the Applet. It is invoked only once.

public void start(): is invoked after the init() method or browser is maximized. It
is used to start the Applet.

public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.

public void destroy(): is used to destroy the Applet. It is invoked only once.

The Component class provides 1 life cycle method of applet.

public void paint(Graphics g): is used to paint the Applet. It provides Graphics
class object that can be used for drawing oval, rectangle, arc etc.
How to run an Applet
To execute the applet by appletviewer tool, create an
There are two ways to run an applet By html file. applet that contains applet tag in comment and compile it.

By appletViewer tool (for testing purpose).


//First.java To execute the applet by appletviewer tool, write in command
import java.applet.Applet; prompt:
import java.awt.Graphics;
public class First extends Applet{ c:\>javac First.java
c:\>appletviewer First.html
public void paint(Graphics g){
g.drawString("welcome",150,150);
}}

To execute the applet by html file, create an applet and compile it.
After that create an html file and place the applet code in html file.
Now click the html file.

<html> <body>
<applet code="First.class" width="300" height="300">
</applet> </body> </html>
Commonly used methods of Graphics class:
public abstract void drawString(String str, int x, int y): is used to draw the specified string.

public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified
width and height.

public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with the
default color and specified width and height.

public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the
specified width and height.

public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the default
color and specified width and height.
public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the
points(x1, y1) and (x2, y2).

public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used
draw the specified image.
public abstract void drawArc(int x, int y, int width, int
height, int startAngle, int arcAngle): is used draw a import java.applet.Applet;
circular or elliptical arc.
import java.awt.*;

public abstract void fillArc(int x, int y, int width, int public class GraphicsDemo extends Applet{
height, int startAngle, int arcAngle): is used to fill a
circular or elliptical arc.
public void paint(Graphics g){
public abstract void setColor(Color c): is used to set the g.setColor(Color.red);
graphics current color to the specified color. g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
public abstract void setFont(Font font): is used to set the g.fillRect(170,100,30,30);
graphics current font to the specified font. g.drawOval(70,200,30,30);

g.setColor(Color.pink);
<html> g.fillOval(170,200,30,30);
<body> g.drawArc(90,150,30,30,30,270);
<applet code="GraphicsDemo.class" width="300" height="300"> g.fillArc(270,150,30,30,0,180);
</applet>
</body> } }
</html>

You might also like