Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
2 views55 pages

Unit 3 &4

Socker X

Uploaded by

fack20k
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views55 pages

Unit 3 &4

Socker X

Uploaded by

fack20k
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 55

UNIT 3

1.Inheritance
 Inheritance in Java is a mechanism in which one object acquires all the properties
and behaviors of a parent object. ...

 The idea behind inheritance in Java is that you can create new classes that are built
upon existing classes. When you inherit from an existing class, you can reuse
methods and fields of the parent class.

extends Keyword

extends is the keyword used to inherit the properties of a class. Following is the
syntax of extends keyword.

Syntax

class Super
{
.....
}
class Sub extends Super
{
.....
.....
}
 Super Class: The class whose features are inherited is known as super class(or a
base class or a parent class).

 Sub Class: The class that inherits the other class is known as sub class(or a derived
class, extended class, or child class). The subclass can add its own fields and
methods in addition to the superclass fields and methods.

 Reusability: Inheritance supports the concept of “reusability”, i.e. when we want


to create a new class and there is already a class that includes some of the code that
we want, we can derive our new class from the existing class

1
Single Inheritance :(One base ,One sub class):

Single Inheritance :

In single inheritance, subclasses inherit the features of one superclass. In image


below, the class A serves as a base class for the derived class B

Syntax
class Super-class name
{
}
class Sub-classname extends Super-class name
{
}
Example
class aaa
{
}
class bbb extends aaa
{
}
Multilevel Inheritance-(One base One sub one or more than one intermediate)

 Multilevel Inheritance : In Multilevel Inheritance, a derived class will be


inheriting a base class and as well as the derived class also act as the base class to
other class.

2
Example

class aaa

class bbb extends aaa

class ccc extends bbb

Hierarchical- (One base ,More than one sub)

Hierarchical Inheritance : In Hierarchical Inheritance, one class serves as a


superclass (base class) for more than one sub class.In below image, the class A serves as a
base class for the derived class B,C and D.

3
Example

class aaa

class bbb extends aaa

class ccc extends aaa

Multiple Inheritance (Through Interfaces) :

In Multiple inheritance ,one class can have more than one superclass and inherit
features from all parent classes. Please note that Java does not support multiple
inheritance with classes

4
Hybrid Inheritance-More than one type of Inheritance

 Hybrid Inheritance(Through Interfaces) : It is a mix of two or more of the above


types of inheritance. Since java doesn’t support multiple inheritance with classes,
the hybrid inheritance is also not possible with classes.

Access Modifiers in Java

Example Program-1

class Teacher

String designation = "Teacher";

String collegeName = "Beginnersbook";

void aaa()

System.out.println("Teaching");

public class PhysicsTeacher extends Teacher

5
{

String mainSubject = "Physics";

public static void main(String args[])

PhysicsTeacher obj = new PhysicsTeacher(); System.out.println(obj.collegeName);

System.out.println(obj.designation);

System.out.println(obj.mainSubject);

obj.aaa()

}}

Example Program-2

Import java.io.*;
class Animal
{
public void eat()
{
System.out.println("I can eat");
}
public void sleep()
{
System.out.println("I can sleep");
}
}
class Dog extends Animal
{
public void bark()
{
System.out.println("I can bark");
}}
class Main
{
public static void main(String[] args)
{
Dog dog1 = new Dog();
dog1.eat();

6
dog1.sleep();
dog1.bark();
}}

2.Interface
 An interface is a completely "abstract class" that is used to group related methods
with empty bodies.

 To access the interface methods, the interface must be "implemented“ by another


class with the implements keyword (instead of extends).

 The body of the interface method is provided by the "implement" class

 An interface in Java is a blueprint of a class. It has static constants and abstract


methods.

 The interface in Java is a mechanism to achieve abstraction. There can be only


abstract methods in the Java interface, not method body. It is used to achieve
abstraction and multiple inheritance in Java.

Example:

interface Animal

public void animalSound();

public void run();

class dog implements Animal

}
Relationship between class and Interface

 Interface ----class (implements )

 class ---- class (extends)

 Interface ---- Interface (extends)

Multiple Interfaces:

To implement multiple interfaces, separate them with a comma

Multiple Interface

interface aaa
{
}
interface bbb

7
{
}
interface ccc implements aaa,bbb
{
}
Example Program
interface Animal
{
public void animalSound();
public void sleep();
}
class Pig implements Animal
{
public void animalSound()
{
System.out.println("The pig says: wee wee");
}
public void sleep()
{
System.out.println("Zzz");
}
}
class MyMainClass
{
public static void main(String[] args)
{
Pig myPig = new Pig();
myPig.animalSound();
myPig.sleep();
}
}

Out put
The pig says: wee wee
Zzz

3.Package in java .
Package in Java is a mechanism to encapsulate a group of classes, sub packages
and interfaces

A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined
package.

8
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util,
sql etc.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Types of packages:

Predefine Package

a.Built-in Packages
These packages consist of a large number of classes which are a part of Java API.Some of
the commonly used built-in packages are:
java.lang:

Contains language support classes(e.g classed which defines primitive data types,
math operations). This package is automatically imported.
java.io:

Contains classed for supporting input / output operations.


java.util:

9
Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
java.applet:

Contains classes for creating Applets.


java.awt:

Contain classes for implementing the components for graphical user interfaces (like
button , ;menus etc).

java.net:

Contain classes for supporting networking operations.

b.User-definedpackages
These are the packages that are defined by the user. First we create a package using
package keyword. While creating a package, programmers must choose a name for the
package and include a package statement program that contains the classes, interfaces,
enumerations, and annotation types that you want to include in the package.

Creating a Package

To create a package, you choose a name for the package (and put
a package statement with that name at the top of every source file that contains the types
(classes, interfaces, enumerations, and annotation types) that you want to include in
the package.

Syntax

package nameOfPackage;

class class-name

{----}

Example

package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
Importing package

import keyword is used to import built-in and user-defined packages into


your java source file so that your class can refer to a class that is in another package by
directly using its name

Using packagename.*

package pack;

10
public class A
{
public void msg(){System.out.println("Hello");}
}

import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

Using packagename.classname

package pack;
public class A
{
public void msg(){System.out.println("Hello");}
}

import pack.A;
class B
{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Sub package

Package inside the package is known as subpackage. Thepackages that come lower
in the naming hierarchy are called "sub package" of the corresponding package higher in
the hierarchy i.e. the package that we are putting into another package is called "sub
package"

Example program

package mypack;

public class balance

String name;

double bal;

public balance(String n, double b) {

11
name=n;

bal=b;

public void show() {

if(bal>0) {

System.out.print(“”);

System.out.println(name+”$”+bal);

else

System.out.println(“negative value”);

import mypack.*;

class testBalance

public static void main(String arg[]) {

balance test=new balance(“j.j.jaspers”,-99.88);

test.show();

}
OUTPUT:

j.j.jaspers $ 99.88

Unit -4

1.Exception handling
Exception

An exception is an event, which occurs during the execution of a program, that


disrupts the normal flow of the program's instructions. When an error occurs within a
method, the method creates an object and hands it off to the runtime system. ... This block
of code is called an exception handler.

Exception handling?

Exception is the place where a problem has occurred, Handling is the place for the
solution to the specific exception.

12
Use try block to write code that may disrupts the normal program flow Use catch block to
handle it

Try
{
// Block of code to try
}
catch(Exception e)
{
// Block of code to handle errors
}
Types of Exception

 RunTimeException or Unchecked Exception

 CompileTimeException or checked Exception

 Error

Example Program-1

public class JavaExceptionExample


{
public static void main(String args[])
{
Try
{
int data=100/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
//rest code of the program.
Example Program-2

public class MyClass


{
public static void main(String[ ] args)
{
int myNumbers[] = {1, 2, 3};

13
System.out.println(myNumbers[1]);
System.out.println(myNumbers[2]);
System.out.println(myNumbers[10]);
// error!
}
}
Example Program-3
public class MyClass
{
public static void main(String[ ] args)
{
try
{
int myNumbers[] = {1, 2, 3};
System.out.println(myNumbers[10]);
}
catch (Exception e)
{
System.out.println("Something went wrong.");
}}
}
RuntimeException or Unchecked Exception
These type of exception can be easily validated during code
development. A developer can avoid this exception completely in their application by
writing good validation. Exception that are subclass of RuntimeException are called as
Unchecked Exception
Example
ArithmeticException
NumberFormatException
NullpointerException
CompileTimeException or checked Exception
Exception that cannot be validated during development are called checked
Exception, the compiler will force you to use try catch block or to throws the
exception.
Example
FileNotFoundException
SQLException
14
InterruptedException
Error
An Error is a subclass of Throwable that indicates serious problems that a
reasonable application should not try to catch. Most such errors are abnormal
conditions. That is, Error and its subclasses are regarded as unchecked exceptions for
the purposes of compile-time checking of exceptions.
Example
IOError
LinkageError
VirtualMachineError

Try block
The try block contains set of statements where an exception can occur. A try block is
always followed by a catch block, which handles the exception that occurs in
associated try block. A try block must be followed by catch blocks or finally block or
both.
Syntax:
try
{
//statements that may cause an exception
}

Catch block

15
A catch block is where you handle the exceptions, this block must follow the try
block. A single try block can have several catch blocks associated with it. You can
catch different exceptions in different catch blocks. When an exception occurs in try
block, the corresponding catch block that handles that particular exception executes.
Syntax
try
{
//statements that may cause an exception
} catch (exception(type) e(object))
{
//error handling code
}
Multiple catch blocks
A try block can be followed by one or more catch blocks. Each catch block must
contain a different exception handler. So, if you have to perform different tasks at the
occurrence of different exceptions, use java multi-catch block.
 At a time only one exception occurs and at a time only one catch block is executed.
 All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception
Finally block
A finally block contains all the crucial statements that must be executed whether
exception occurs or not.
try
{
//Statements that may cause an exception
}
Catch
{
//Handling exception
}
finally
{
//Statements to be executed
}
Throw and Throws

16

Finally and Close()


close() statement is used to close all the open streams in a program. Its a good practice
to use close() inside finally block.
finally{
Obj.close();
}
Finally block and System.exit()
System.exit() statement behaves differently than return statement. Unlike return
statement whenever System.exit() gets called in try block then Finally block doesn’t
execute.
try
{
System.out.println("Inside try block");
System.exit(0)
}
Types of Exception in Java with Examples
 ArithmeticException
It is thrown when an exceptional condition has occurred in an arithmetic operation.
 ArrayIndexOutOfBoundsException
It is thrown to indicate that an array has been accessed with an illegal index. The
index is either negative or greater than or equal to the size of the array.
 ClassNotFoundException
This Exception is raised when we try to access a class whose definition is not found
 FileNotFoundException
This Exception is raised when a file is not accessible or does not open.
 IOException
It is thrown when an input-output operation failed or interrupted

17
 InterruptedException
It is thrown when a thread is waiting , sleeping , or doing some processing , and it
is interrupted.
 InterruptedException
It is thrown when a thread is waiting , sleeping , or doing some processing , and it
is interrupted.
 NoSuchFieldException
It is thrown when a class does not contain the field (or variable) specified
 NoSuchMethodException
It is thrown when accessing a method which is not found.
 NullPointerException
This exception is raised when referring to the members of a null object. Null
represents nothing
 NumberFormatException
This exception is raised when a method could not convert a string into a numeric
format.
 RuntimeException
This represents any exception which occurs during runtime.
 StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either negative than
the size of the string

2.Thread
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking
to utilize the CPU. Multitasking can be achieved in two ways:
 Process-based Multitasking (Multiprocessing)
 Thread-based Multitasking (Multithreading)
1) Process-based Multitasking (Multiprocessing)
Each process has an address in memory. In other words, each process allocates a
separate memory area.
A process is heavyweight.
Cost of communication between the process is high.
Switching from one process to another requires some time for saving and
loading registers, memory maps, updating lists, etc.
2) Thread-based Multitasking (Multithreading)
Threads share the same address space.
A thread is lightweight.
Cost of communication between the thread is low.
Thread
 A thread is a lightweight sub process, the smallest unit of processing. It is a
separate path of execution.

18
 Threads are independent. If there occurs exception in one thread, it doesn't affect
other threads. It uses a shared memory area.

Multithread

Multithreading
 Multithreading in Java is a process of executing multiple threads
simultaneously.
 A thread is a lightweight sub-process, the smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking.
 However, we use multithreading than multiprocessing because threads use a
shared memory area. They don't allocate separate memory area so saves
memory, and context-switching between the threads takes less time than
process.
Advantages of Java Multithreading

19
 1) It doesn't block the user because threads are independent and you can
perform multiple operations at the same time.
 2) You can perform many operations together, so it saves time.
 3) Threads are independent, so it doesn't affect other threads if an exception
occurs in a single thread.
Thread Life Cycle

New
When we create a new Thread object using new operator, thread state is New
Thread. At this point, thread is not alive and it’s a state internal to Java
programming.
Runnable
When we call start() function on Thread object, it’s state is changed to
Runnable. The control is given to Thread scheduler to finish it’s execution. Whether
to run this thread instantly or keep it in runnable thread pool before running,
depends on the OS implementation of thread scheduler.
Example
MyThread t1 = new MyThread();
t1.start();
Running
 When thread is executing, it’s state is changed to Running. Thread scheduler
picks one of the thread from the runnable thread pool and change it’s state to
Running.

20
 Then CPU starts executing this thread. A thread can change state to
Runnable, Dead or Blocked from running state depends on time slicing,
thread completion of run() method or waiting for some resources.
 Schedule()
 yield(()
Blocked/Waiting state:
When a thread is temporarily inactive, then it’s in one of the following states.
 Blocked
 Waiting
For example, when a thread is waiting for I/O to complete, it lies in the
blocked state. It’s the responsibility of the thread scheduler to reactivate and
schedule a blocked/waiting thread.
 suspend()
 wait()
 sleep(t)
 notify()
 notifyAll()
 resume()
A thread in this state cannot continue its execution any further until it is
moved to runnable state.
Terminated (Dead)
A runnable thread enters the terminated state when it completes its task or otherwise
terminates.
Dead state means that a thread has finished its execution or its run() method and
when the stop() method is invoke. The stop() method kills the thread and
the thread doesn't work further
Example
t1.stop();
Thread Methods
 public void run(): is used to perform action for a thread.
 public void start(): starts the execution of the thread.JVM calls the run()
method on the thread.
 public void sleep(long miliseconds): Causes the currently executing thread to
sleep (temporarily cease execution) for the specified number of milliseconds.
 public void join(): waits for a thread to die.
 public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.

21
 public int getPriority(): returns the priority of the thread.
 public int setPriority(int priority): changes the priority of the thread.
 public String getName(): returns the name of the thread.
 public Thread currentThread(): returns the reference of currently executing
thread.
 public int getId(): returns the id of the thread.
 public boolean isAlive(): tests if the thread is alive.
 public void yield(): causes the currently executing thread object to
temporarily pause and allow other threads to execute.
 public void suspend(): is used to suspend the thread(depricated).
 public void resume(): is used to resume the suspended thread(depricated).
 public void stop(): is used to stop the thread(depricated)
Create a Thread
There are two ways to create a thread:
 By extending Thread class
 By implementing Runnable interface.
Thread class
Thread class provide constructors and methods to create and perform
operations on a thread. Thread class extends Object class and implements Runnable
interface.
Commonly used Constructors of Thread class:
 Thread()
 Thread(String name)
 Thread(Runnable r)
 Thread(Runnable r,String name)
By extending the Thread class
 We create a class that extends the java.lang.Thread class. This class
overrides the run() method available in the Thread class. A thread begins its
life inside run() method.
 We create an object of our new class and call start() method to start the
execution of a thread. Start() invokes the run() method on the Thread object
Example
class class_name extends Thread
Example Program-extends thread
class MultithreadingDemo extends Thread
{
22
public void run()
{
System.out.println("My thread is in running state.");
}
public static void main(String args[])
{
MultithreadingDemo obj=new MultithreadingDemo();
obj.start();
}}
By implementing the Runnable interface.
 We create a new class which implements java.lang.Runnable interface and
override run() method.
 Then we instantiate a Thread object and call start() method on this object.
 Runnable is a interface name .
Example
class class_name implements Runnable
Example Program-implements Runnable
class Multi3 implements Runnable
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
Priority of a Thread (Thread Priority):
 Each thread have a priority. Priorities are represented by a number between 1
and 10. In most cases, thread scheduler schedules the threads according to

23
their priority (known as pre-emptive scheduling). But it is not guaranteed
because it depends on JVM specification that which scheduling it chooses.

 The minimum thread priority in java is 1 and maximum or highest


thread priority is 10. We will see a program example to set and get thread
priority. Default priority of thread in java is = 5. We can set priority of a
thread within this range only.

Thread Priority
 public static int MIN_PRIORITY(1)
 public static int NORM_PRIORITY(5)
 public static int MAX_PRIORITY(10)
Get and Set methods in Thread priority
 getPriority()
 setPriority(intnewPriority)
Example Program(1) –Thread Priority
class TestMultiPriority1 extends Thread
{
public void run()
{
System.out.println("running thread name
is:"+Thread.currentThread().getName());
System.out.println("running thread priority
is:"+Thread.currentThread().getPriority());
}
public static void main(String args[])
{
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}}
OUTPUT
running thread name is:Thread-0

24
running thread priority is:10
running thread name is:Thread-1

running thread priority is:1


Example Program(2) –Thread Priority
class MyThread extends Thread
{
public void run()
{
System.out.println("Thread Running...");
}
public static void main(String[]args)
{
MyThread p1 = new MyThread();
p1.start(); // Starting thread
p1.setPriority(2); //Setting priority
int p = p1.getPriority();// Getting priority
System.out.println("thread priority : " + p);
}}
Synchronization
 Multi-threaded programs may often come to a situation where multiple
threads try to access the same resources and finally produce erroneous and
unforeseen results.

 Java provides a way of creating threads and synchronizing their task by using
synchronized blocks. Synchronized blocks in Java are marked with the
synchronized keyword. A synchronized block in Java is synchronized on
some object.

 All synchronized blocks synchronized on the same object can only have one
thread executing inside them at a time. All other threads attempting to enter
the synchronized block are blocked until the thread inside the synchronized
block exits the block.

 This synchronization is implemented in Java with a concept called


monitors. Only one thread can own a monitor at a given time. When a thread
acquires a lock, it is said to have entered the monitor. All other threads
attempting to enter the locked monitor will be suspended until the first thread
exits the monitor.

Why use Synchronization

25
 To prevent thread interference.

 To prevent consistency problem.

Types of Synchronization

 Process Synchronization

 Thread Synchronization

Mutual Exclusive

 Synchronized method.

 Synchronized block.

 static synchronization.

Synchronization block

26
Example Program
class Table
{
synchronized void printTable(int n)
{
//synchronized method
for(int i=1;i<=5;i++)
{

27
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e){System.out.println(e);
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}
public class TestSynchronization2

28
{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output
5
10
15
20
25
100
200
300
400
500

3.Applet
 An applet is a Java program that runs in a Web browser. ... An applet is
a Java class that extends the java. applet. Applet class. A main() method is
not invoked on an applet, and an applet class will not define main().
 Applet is a special type of program that is embedded in the webpage to
generate the dynamic content. It runs inside the browser and works at client
side.

Advantage
 It works at client side so less response time.
 Secured
 It can be executed by browsers running under many plateforms, including
Linux, Windows, Mac Os etc.

29
 All applets are sub-classes (either directly or indirectly)
of java.applet.Applet class.
 Applets are not stand-alone programs. Instead, they run within either a web
browser or an applet viewer. JDK provides a standard applet viewer tool
called applet viewer.
 In general, execution of an applet does not begin at main() method.
 Output of an applet window is not performed by System.out.println(). Rather
it is handled with various AWT methods, such as drawString().
Difference between Applet and Application

Java Applets are small Java


Java Applications are the stand-alone programs which programs which are designed
can be executed independently to exist within HTML web
document
Java Applications must have main() method for them Java Applets do not need
to execute main() for execution
Java Applets cannot run
Java Applications just needs the JRE independently and require
API’s
Java Applications do not need to extend any class Java Applets must extend
unless required java.applet.Applet class

Java Applications can execute codes from the local Java Applets Applications
system cannot do so

Java Applets has access only


to the browser-specific
Java Applications has access to all the resources
services
available in your system

Example Program
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{
public void paint(Graphics g)
{
g.drawString("welcome",150,150);
}}
Html Program
<html>
<body>
<applet code="First.class" width="300" height="300">
30
</applet>
</body>
</html>
Applet Life Cycle

Applet Methods
 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. Note that init( ) is called .
 paint( ) is also called when the applet begins execution. Whatever the cause,
whenever the applet must redraw its output, paint( ) is called.
 stop( ) : The stop( ) method is called when a web browser leaves the HTML
document containing the applet—when it goes to another page. You 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 user returns to the page.
 destroy( ) : The destroy( ) method is called when the environment determines that
your applet needs to be removed completely from memory. At this point, you
should free up any resources the applet may be using. The stop( ) method is always
called before destroy( ).
Applet Hierarchy in Java

 class java.lang.Object
 class java.awt.Component
 class java.awt.Container
class java.awt.Panel
class java.applet.Applet

31
Example Program-1
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet
{
int height, width;
public void init()
{
height = getSize().height;
width = getSize().width;
setName("MyApplet");
}
public void paint(Graphics g)
{
g.drawRoundRect(10, 30, 120, 120, 2, 3);
}}
<html>
<body>
<applet code=“MyApplet.class" width="300" height="">
</applet>
</body>
</html>

32
Example Program-2
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo1 extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.black);
g.drawString("Welcome to studytonight",50, 50); g.setColor(Color.blue);
g.fillOval(170,200,30,30); g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
g.drawLine(21,31,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
}}
<html>
<body>
<applet code="GraphicsDemo1.class" width="300" height="300">
</applet>
</body>
</html>

OutPut

33
Passing Parameter in Applet
We can get any information from the HTML file as a parameter. For this
purpose, Applet class provides a method named getParameter().
Syntax
public String getParameter(String parameterName)
Steps
 To pass the parameters to the Applet we need to use the param attribute
of <applet> tag.
 To retrieve a parameter's value, we need to use
the getParameter() method of Applet class.
Example
import java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet
{
public void paint(Graphics g)
{
String str=getParameter("msg");
g.drawString(str,50, 50);
34
}
}
<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>
Output:
Welcome to Applet
Unit 5

1.Stream classes in java


A stream is a method to sequentially access a file. I/O Stream means an
input source or output destination representing different types of sources e.g. disk files.
The java.io package provides classes that allow you to convert between Unicode
character streams and byte streams of non-Unicode text
Stream – A sequence of data.
Input Stream: reads data from source.
Output Stream: writes data to destination.

Uses of io stream in java.

Java Byte streams are used to perform input and output of 8-bit bytes,
whereas Java Character streams are used to perform input and output for 16-bit unicode.

Though there are many classes related to character streams but the most frequently
used classes are, FileReader and FileWriter.

Types of Streams in java

 Byte Stream classes


 Character Stream classes

A ) Byte stream classes.

Java Byte streams are used to perform input and output of 8-bit bytes. Byte stream
is defined by using two abstract class at the top of hierarchy, they are InputStream and
OutputStream. For example FileInputStream is used to read from source and
FileOutputStream to write to the destination.

35
 BufferedInputStream -Used for Buffered Input Stream.
 BufferedOutputStream -Used for Buffered Output Stream.
 DataInputStream - Contains method for reading java standard datatype
 DataOutputStream- - An output stream that contain method for writing java
standard data type
 FileInputStream- Input stream that reads from a file
 FileOutputStream - Output stream that write to a file.
 InputStream - Abstract class that describe stream input.
 OutputStream -Abstract class that describe stream output.
 PrintStream - Output Stream that contain print() and println() method
Read Console input in java

Sub classes for Input Stream and Output Stream

36
Input streams - for reading data from streams

Input Stream Class in Java. InputStream class is the superclass of all the io classes i.e.
representing an input stream of bytes. It represents input stream of bytes. Applications that
are defining subclass of InputStream must provide method, returning the next byte of
input
Input stream Constructor :

 InputStream() : Single Constructor

Method in Input Stream

37
Output Stream

OutputStream class is the superclass of all classes representing an output stream of


bytes. An output stream accepts output bytes and sends them to some sink.Applications
that need to define a subclass of OutputStream must always provide at least a method that
writes one byte of output.

Output Stream constructor

 OutputStream() : Single Constructor

Methods in Output Stream

void close() : Closes this output stream and releases any system resources associated with
this stream

void flush() : Flushes this output stream and forces any buffered output bytes to be
written output

void write(byte[] b) : Writes b.length bytes from the specified byte array to this output
stream

void write(byte[] b, int off, int len) : Writes len bytes from the specified byte array
starting at offset off to this output stream.

abstract void write(int b) : Writes the specified byte to this output stream

B) Character Stream classes in java

Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java
Character streams are used to perform input and output for 16-bit unicode. Though there
are many classes related to character streams but the most frequently used classes are,
FileReader and FileWriter.

BufferedReader - Handles buffered input stream.


BufferedWriter- Handles buffered output stream.
FileReader- Input stream that reads from file.
FileWriter- Output stream that writes to file.
InputStreamReader -Input stream that translate byte to character
OutputStreamReader -Output stream that translate character to byte.

38
PrintWriter -Output Stream that contain print() and println() method.
Reader -Abstract class that define character stream input
Writer -Abstract class that define character stream output

Sub Classes in Reader and Writer class

Reader class

Reader classes are used to read 16-bit unicode characters from the input stream.
The Reader class is the superclass for all character-oriented input stream classes. All the
methods of this class throw an IOException. Being an abstract class, the Reader class
cannot be instantiated hence its subclasses are used.

Constructor in Reader class

Reader() It creates a new character-stream reader whose critical sections will


synchronize on the reader itself
Reader(Object lock) It creates a new character-stream reader whose critical
sections will synchronize on the given object.
Methods in Reader class;

close() It closes the stream and releases any system resources associated with it.
mark(int readAheadLimit) It marks the present position in the stream.
read() It reads a single character.
read(char[] cbuf) It reads characters into an array.
ready() It tells whethe
reset()It resets the stream.r this stream is ready to be read.
Writer class

39
Writer classes are used to write 16-bit Unicode characters onto an outputstream.
The Writer class is the superclass for all character-oriented output stream classes .All the
methods of this class throw an IOException. Being an abstract class, the Writer class
cannot be instantiated hence, its subclasses are used
Constructor in Writer class

Writer() It creates a new character-stream writer whose critical sections will synchronize
on the writer itself.

Writer(Object lock) It creates a new character-stream writer whose critical sections will
synchronize on the given object.

Writer class method:


append(char c) It appends the specified character to this writer.
close() It closes the stream, flushing it first.

flush() It flushes the stream.

write(char[] cbuf) : It writes an array of characters.

write(int c) It writes a single character.

2. Utility Classes in java


Utility class is classes that defines a set of methods that perform common, often re-
used functions.Examples of utility classes include java.util.Collections which provides
several utility methods (such as sorting) on objects that implement a Collection
(java.util.collection)

Date class

The class Date represents a specific instant in time, with millisecond precision. The
Date class of java.util package implements Serializable, Cloneable and Comparable
interface. It provides constructors and methods to deal with date and time with java.

Constructor in Date class.

 Date() : Creates date object representing current date and time.


 Date(long milliseconds) : Creates a date object for the given milliseconds since
January 1, 1970, 00:00:00 GMT.
 Date(int year, int month, int date)
 Date(int year, int month, int date, int hrs, int min)
 Date(int year, int month, int date, int hrs, int min, int sec)
 Date(String s).
Methods in Date class.
 boolean after(Date date) : Tests if current date is after the given date.
 boolean before(Date date) : Tests if current date is before the given date.
 int compareTo(Date date) : Compares current date with given date. Returns 0 if
the argument Date is equal to the Date

40
 long getTime() : Returns the number of milliseconds since January 1, 1970,
00:00:00 GMT represented by this Date object.
 void setTime(long time) : Changes the current date and time to given time.
Example Program:

import java.util.Date;

class DateDemo

public static void main(String args[])

Date date = new Date ();

System.out.println (date);

long msec = date.getTime();

System.out.println ("Milliseconds since Jan. 1, 1970 GMT = " + msec);

OUTPUT:

Fri Sep 25 20:11:45 IST 2015

Milliseconds since Sep.25, 2015 GMT = 1443192105482

Calendar class

Calendar class in Java is an abstract class that provides methods for converting date
between a specific instant in time and a set of calendar fields such as MONTH, YEAR,
HOUR, etc. It inherits Object class and implements the Comparable, Serializable,
Cloneable interfaces.
As it is an Abstract class, so we cannot use a constructor to create an instance.
Instead, we will have to use the static method Calendar.getInstance() to instantiate and
implement a sub-class.
Methods used in Calender class.
 Calendar.getInstance(): return a Calendar instance based on the current time in
the default time zone with the default locale.
 Calendar.getInstance(TimeZone zone)
 Calendar.getInstance(Locale aLocale)
 Calendar.getInstance(TimeZone zone, Locale aLocale)

Example program
import java.util.*;

class GregorianCalendarDemo

public static void main(String args[])


41
{

String months[ ] = {"Jan", "Feb", "Mar", "Apr","May", "Jun", "Jul", "Aug", "Sep", "Oct",
"Nov", "Dec"};

int year;

GregorianCalendar gcalendar = new GregorianCalendar();

System.out.print("Date: ");

System.out.print(months[gcalendar.get(Calendar.MONTH)]);

System.out.print(" " + gcalendar.get(Calendar.DATE) + " ");

System.out.println(year = gcalendar.get(Calendar.YEAR));

System.out.print("Time: ");

System.out.print(gcalendar.get(Calendar.HOUR) + ":");

System.out.print(gcalendar.get(Calendar.MINUTE) + ":");

System.out.println(gcalendar.get(Calendar.SECOND));

if(gcalendar.isLeapYear(year)) {

System.out.println("The current year is a leap year");

else

{ System.out.println("The current year is not a leap year");

}}}

OUTPUT:

Date: Sep 25 2015

Time: 8:17:42

The current year is not a leap year

Random class

An instance of java Random class is used to generate random numbers.


This class provides several methods to generate random numbers of type integer, double,
long, float etc. Random number generation algorithm works on the seed value. If not
provided, seed value is created from system nano time.

Constructors in random class:

 Random(): Creates a new random number generator


 Random(long seed): Creates a new random number generator using a single long
seed
Methods in Random class.

42
 java.util.Random.doubles(): Returns an effectively unlimited stream of pseudo
random double values,
 java.util.Random.ints(): Returns an effectively unlimited stream of pseudo random
int values
 java.util.Random.longs(): Returns an effectively unlimited stream of pseudo
random long values.
Scanner class

The Scanner class is used to get user input, and it is found in the java.util package.

To use the Scanner class, create an object of the class and use any of the available
methods found in the Scanner class documentation. In our example, we will use
the nextLine() method, which is used to read Strings

Methods used in Scanner class

 nextBoolean() Reads a boolean value from the user

 nextByte() Reads a byte value from the user

 nextDouble() :Reads a double value from the user

 nextFloat() Reads a float value from the user

 nextInt() Reads a int value from the user

 nextLine() Reads a String value from the user

 nextLong() Reads a long value from the user

 nextShort() Reads a short value from the user

Example Program

import java.io.*;

import java.util.Scanner;

public class Add

public static void main(String[] args)

int num1, num2, sum;

Scanner sc = new Scanner(System.in);

System.out.println("Enter First Number: ");

num1 = sc.nextInt();

43
System.out.println("Enter Second Number: ");

num2 = sc.nextInt();

sc.close();

sum = num1 + num2;System.out.println("Sum of these numbers: "+sum);

String Tokenizer class

String Tokenizer class in Java is used to break a string into tokens. Example:
A String Tokenizer object internally maintains a current position within the string to be
tokenized .A token is returned by taking a substring of the string that was used to create
the String Tokenizer object.

Constructor used in String Tokenizer

 String Tokenizer(String str): creates StringTokenizer with specified string.


 String Tokenizer(String str, String delim): creates StringTokenizer with
specified string and delimeter.
 String Tokenizer(String str, String delim, boolean returnValue): creates String
Tokenizer with specified string, delimeter and returnValue. If return value is true,
delimiter characters are considered to be tokens. If it is false, delimiter characters
serve to separate tokens.
Methods used in String Tokenizer.
 boolean hasMoreTokens() - bchecks if there is more tokens available.
 String nextToken() - returns the next token from the StringTokenizer object.
 String nextToken(String delim) -returns the next token based on the delimeter.
 boolean hasMoreElements() - same as hasMoreTokens() method.
 Object nextElement() - same as nextToken() but its return type is Object.
 int countTokens() - returns the total number of tokens.
Example Program

import java.util.StringTokenizer;
public class Simple
{
public static void main(String args[])
{
StringTokenizer st = new StringTokenizer("my name is khan"," ");
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
44
}
}
}
Output:
my
name
is
khan

3. FILES IN JAVA

Some of the common file handling operations are;

1. Create file
2. Delete file
3. Open file
4. Close file
5. Read file
6. Write file
7. Change files permissions.
8. Check file permission
9. Rename of file
10. Getting the name of file
11. Getting the size of file

Create File

We can use File class createNewFile() method to create new file. This method returns true
if file is successfully created, otherwise it returns false. Once creating file following steps
should be follow:

 Suitable name for file


 Data Types to be stored
 Purpose (Reading ,Writing, Updating)
 Methods of creating file

Delete File

File class delete method is used to delete a file or an empty directory

Read File

There are many ways to read a file in java. We can use BufferedReader, FileReader or
Files class

FileReader

 This class inherit from the InputStreamReader Class.


 The constructors of this class assume that the default character encoding and the
default byte-buffer size are appropriate.

45
 FileReader is meant for reading streams of characters. For reading streams of raw
bytes, consider using a FileInputStream.

Constructors:

 FileReader(File file) - Creates a FileReader , given the File to read from


 FileReader(FileDescripter fd) - Creates a new FileReader , given the
FileDescripter to read from
 FileReader(String fileName) - Creates a new FileReader , given the name of the
file to read from

Methods:

 public int read () throws IOException – Reads a single character. This method
will block until a character is available
 public int read(char[] cbuff) throws IOException – Reads characters into an
array. This method will block until some input is available

Write File

We can use FileWriter, BufferedWriter, Files or FileOutputStream to write file in java.

FileWriter

 This class inherits from the OutputStream class.


 The constructors of this class assume that the default character encoding and the
default byte-buffer size are acceptable.

 FileWriter is meant for writing streams of characters.


 FileWriter creates the output file , if it is not present already.

Constructors:

 FileWriter(File file) - Constructs a FileWriter object given a File object.


 FileWriter (File file, boolean append) - constructs a FileWriter object given a File
object.
 FileWriter (FileDescriptor fd) - constructs a FileWriter object associated with a
file descriptor.
 FileWriter (String fileName) - constructs a FileWriter object given a file name.
 FileWriter (String fileName, Boolean append) - Constructs a FileWriter object
given a file name with a Boolean indicating whether or not to append the data
written.

Methods:

 public void write (int c) throws IOException – Writes a single character.

46
 public void write (char [] stir) throws IOException – Writes an array of
characters.
 public void write(String str)throws IOException – Writes a string.

File Permissions

File class provide methods to get file permission details as well as change them.
Java provides a number of method calls to check and change the permission of a file, such
as a read-only file can be changed to have permissions to write.

File permissions are required to be changed when the user want to restrict the
operations permissible on a file. For example, a file permission can be changed from write
to read-only because the user no longer want to edit the file.

1. Checking the file permissions

Executable:

Tests whether the application can execute the file denoted by this abstract path
name.

Syntax

public boolean canExecute()

Readable:

Tests whether the application can read the file denoted by this abstract path name.

Syntax

public boolean canRead()

Writable:

Tests whether the application can modify the file denoted by this abstract path
name.

Syntax

public boolean canWrite()

2. Changing file permissions

setExecutable

A convenience method to set the owner’s execute permission for this abstract path
name

Syntax

public boolean setExecutable(boolean executable)

47
setReadable:

A convenience method to set the owner’s read permission for this abstract path name

Syntax

public boolean setReadable(boolean readable)

setWritable:

A convenience method to set the owner’s write permission for this abstract path
name.

Syntax

public boolean setWritable(boolean writable)

4. Event in java
Change in the state of an object is known as event i.e. event describes the change
in state of source. Events are generated as result of user interaction with the graphical
user interface components.
For example, clicking on a button, moving the mouse, entering a character through
keyboard, selecting an item from list, scrolling the page are the activities that causes an
event to happen.

Types of Event

 Foreground Events - Those events which require the direct interaction of user.
For example, clicking on a button, moving the mouse, entering a character through
keyboard, selecting an item from list, scrolling the page etc.
 Background Events - Those events that require the interaction of end user are
known as background events. Operating system interrupts, hardware or software
failure, timer expires, an operation completion are the example of background
events.
Event Handling

Event Handling is the mechanism that controls the event and decides what should
happen if an event occurs. This mechanism has the code which is known as event handler
that is executed when an event occurs. Java Uses the Delegation Event Model to handle
the events.

 Event Source
The source is an object on which event occurs. Source is responsible for providing
information of the occurred event to it's handler. Java provide as with classes for source
object.
 Event Listener
It is also known as event handler. Listener is responsible for generating response to
an event. From java implementation point of view the listener is also an object. Listener
waits until it receives an event. Once the event is received , the listener process the event
an then returns.

48
 Event classes

Event Classes in Java are the classes defined for almost all the components that may
generate events

 ActionEvent : Button, TextField, List, Menu


 WindowEvent : Frame
 ItemEvent : Checkbox, List
 AdjustmentEvent : Scrollbar
 MouseEvent : Mouse
 KeyEvent : Keyboard

 Event Adapters:
Event Adapters classes are abstract class that provides some methods used for
avoiding the heavy coding. Adapter class is defined for the listener that has more than one
abstract method.
Event and Listener (Java Event Handling)

Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

The component with the Listener, many classes provide the registration methods. For example:

Button

public void addActionListener(ActionListener a){}

◦MenuItem

public void addActionListener(ActionListener a){}

◦TextField

49
public void addActionListener(ActionListener a){}

◦public void addTextListener(TextListener a){}

◦TextArea

public void addTextListener(TextListener a){}

◦Checkbox

public void addItemListener(ItemListener a){}

◦Choice

public void addItemListener(ItemListener a){}

◦List

public void addActionListener(ActionListener a){}

public void addItemListener(ItemListener a){}

Example Program

import java.awt.*;

import java.awt.event.*;

class AEvent extends Frame implements ActionListener{

TextField tf;

AEvent(){ .

create components

tf=new TextField();

tf.setBounds(60,50,170,20);

Button b=new Button("click me");

b.setBounds(100,120,80,30);

register listener

b.addActionListener(this);//passing current instance

add components and set size, layout and visibility

add(b);add(tf);

setSize(300,300);

setLayout(null);

setVisible(true);

public void actionPerformed(ActionEvent e){

tf.setText("Welcome");

50
}

public static void main(String args[]){

new AEvent();

} }

Output

5.Legacy Classes and Interface


 Legacy classes and interfaces are the classes and interfaces that formed the
collections framework in the earlier versions of Java and how now been
restructured or re-engineered. They are fully compatible with the framework. ...
All legacy classes were re-engineered to support generic in JDK5.

 Legacy Classes - Java Collections. ... It only defined several classes and
interfaces that provide methods for storing objects. When Collections framework
were added in J2SE 1.2, the original classes were reengineered to support the
collection interface. These classes are also known as Legacy classes.

The following are the legacy classes defined by java.util package

 Dictionary
 HashTable
 Properties
 Stack
 Vector
 There is only one legacy interface called Enumeration

Enumeration interface
 Enumeration interface defines method to enumerate(obtain one at a time) through
collection of objects.

 This interface is superseded(replaced) by Iterator interface.

51
 However, some legacy classes such as Vector and Properties defines several
method in which Enumeration interface is used.

 An enum is a special "class" that represents a group of constants (unchangeable


variables, like final variables).

 To create an enum, use the enum keyword (instead of class or interface), and
separate the constants with a comma.

 Note that they should be in uppercase letters

Vector class
 Vector is similar to ArrayList which represents a dynamic array.

 There are two differences between Vector and ArrayList. First, Vector is
synchronized while ArrayList is not, and Second, it contains many legacy methods
that are not part of the Collections Framework.

 With the release of JDK 5, Vector also implements Iterable. This means that Vector
is fully compatible with collections, and a Vector can have its contents iterated by
the for-each loop.

Vector Constructor

Vector()

This creates a default vector, which has an initial size of 10.

Vector(int size)

This creates a vector whose initial capacity is specified by size.

Vector(int size, int incr)

This creates a vector whose initial capacity is specified by size and whose
increment is specified by incr. Vector(Collection c)

Vector Methods

Method Description

void addElement(E element) adds element to the Vector

E elementAt(int index) returns the element at specified index

Enumeration elements() returns an enumeration of element in vector

E firstElement() returns first element in the Vector

E lastElement() returns last element in the Vector

void removeAllElements() removes all elements of the Vector

52
The Vector class implements a growable array of objects. Vectors basically fall in
legacy classes but now it is fully compatible with collections. It is found in the java.util
package and implements the List interface, so we can use all the methods of List interface
here.

Example Program

import java.io.*;

import java.util.*;

class VectorExample {

public static void main(String[] args)

int n = 5;

Vector<Integer> v = new Vector<Integer>(n);

for (int i = 1; i <= n; i++)

v.add(i);

System.out.println(v);

v.remove(3);

System.out.println(v);

for (int i = 0; i < v.size(); i++)

System.out.print(v.get(i) + " ");

}}

Output
53
[1, 2, 3, 4, 5]

[1, 2, 3, 5]

123

Stack class

 Stack class extends Vector.

 It follows last-in, first-out principle for the stack elements.

 It defines only one default constructor

Stack() //This creates an empty stack

If you want to put an object on the top of the stack, call push() method. If you want
to remove and return the top element, call pop() method. An EmptyStackException is
thrown if you call pop() method when the invoking stack is empty.

boolean empty()

Tests if this stack is empty. Returns true if the stack is empty, and returns false if the
stack contains elements.

Object peek( )

Returns the element on the top of the stack, but does not remove it.

Object pop( )

Returns the element on the top of the stack, removing it in the process.

Object push(Object element)

Pushes the element onto the stack. Element is also returned.

Example Program
import java.util.Stack;

class Main
54
{

public static void main(String[] args)

Stack<String> animals= new Stack<>();

animals.push("Dog");

animals.push("Horse");

animals.push("Cat");

System.out.println("Initial Stack: " + animals);

String element = animals.pop();

System.out.println("Removed Element: " + element);

}}

55

You might also like