Java Unit 3 and 4

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 58

Java Unit 3 , 4

Interface in Java
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.
In other words, you can say that interfaces can have abstract methods
and variables. It cannot have a method body.
Java Interface also represents the IS-A relationship.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
It is used to achieve abstraction.
By interface, we can support the functionality of multiple inheritance.
It can be used to achieve loose coupling.

How to declare an interface?


An interface is declared by using the interface keyword. It provides
total abstraction; means all the methods in an interface are declared
with the empty body, and all the fields are public, static and final by
default. A class that implements an interface must implement all the
methods declared in the interface.
Syntax:
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}

Example
// Interface
interface Animal {
public void animalSound(); // interface method (does not have a
body)
public void sleep(); // interface method (does not have a body)
}

// Pig "implements" the Animal interface


class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}

class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}

Multiple Interfaces
To implement multiple interfaces, separate them with a comma:
Example
interface FirstInterface {
public void myMethod(); // interface method
}

interface SecondInterface {
public void myOtherMethod(); // interface method
}

class DemoClass implements FirstInterface, SecondInterface {


public void myMethod() {
System.out.println("Some text..");
}
public void myOtherMethod() {
System.out.println("Some other text...");
}
}

class Main {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}

What is Abstract class :


A class having keyword “abstract” before its name is known as
abstract class.
A class that is declared using “abstract” keyword is known as abstract
class.
An abstract class cannot be instantiated, which means you are not
allowed to create an object of it.
Points regarding Abstract class:

It can have abstract and non-abstract methods.


It cannot be instantiated.
It can have constructors and static methods also.
It can have final methods which will force the subclass not to change
the body of the method.
If the abstract class includes any abstract method, then all the child
classes inherited from the abstract superclass must provide the
implementation of the abstract method.

Declaration of Abstract class-

Abstract class Language


{
// method of abstract class
public void display()
{ System.out.println("This is Java Programming"); }
}

class Main extends Language


{
public static void main(String[] args)
{ // create an object of Main
Main obj = new Main();
// access method of abstract class
// using object of Main class
obj.display();
}}
OUTPUT: This is Java programming

Abstract Method in Java


A method which is declared as abstract and does not have
implementation is known as an abstract method.
Example of abstract method
abstract void printStatus();//no method body and abstract

Example of Abstract class that has an abstract method or


Implementing Abstract Method :
In this example, Bike is an abstract class that contains only one
abstract method run. Its implementation is provided by the Honda
class.
abstract class Bike{
abstract void run();
}

class Honda extends Bike{


void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
}
}

Output : running safely

Abstract class having constructor, data member and methods:

abstract class Bike{


//constructor
Bike(){
System.out.println("bike is created");
}

//abstract method
abstract void run();
void changeGear(){
System.out.println("gear changed");
}
}
class Honda extends Bike{
void run() {
System.out.println("running safely..");
}
}

class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}

Output: bike is created


running safely
gear changed

final keyword -
If a final keyword is used to before a method name then such type of
method is called final method
The final keyword in java is used to restrict the user. In java final
keyword can be used in many context.
Final can be:
Variable: If variable is final, you cannot change the value of final
variable (It will be constant).
Method: If you make any method as final, you cannot override it.
Class: If you make any class as final, you cannot extend it.

Final Variable-

class Bike{
final int speedlimit=90 ;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike obj=new Bike();
obj.run();
}
}
output: Compile Time Error

Final Method
class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");
}

public static void main(String args[]){


Honda H = new Honda();
H.run();
}
}
Output:Compile Time Error

Final class

final class Bike


{}

class Honda extends Bike


{
void run()
{System.out.println("running safely with 100kmph"); }
public static void main(String args[])
{
Honda honda= new Honda();
honda.run();
} }

Output:Compile Time Error

JAVA - PACKAGES:

What is package:
Packages are used in Java, in-order to avoid name conflicts and to
control access of class, interface and enumeration etc. A package
can be defined as a group of similar types of classes, interface,
enumeration or sub-package.
Using package, it becomes easier to locate the related classes and
it also provides a good structure for projects with hundreds of
classes and other files.
Benefits of using package in java:
Java package is used to categorize the classes and interfaces so
that they can be easily maintained.
Java package provides access protection.
Java package removes naming collision.
This packages can be provide reusability of code.
We can create our own package or extend already available package.

Java Packages: Types:

Built-in Package: Existing Java package for example java.lang


java.util
java.io etc.

User-defined-package: Java package created by user to categorize


their project's classes and interface.

How to Create a package:

Creating a package in java is quite easy. Simply include a package


command followed by name of the package as the first statement
in java source file.

package mypackage; public class student


{
Statement;
}

The above statement will create a package name mypackage in the


project directory.
Java uses file system directories to store packages.
For example the .java file for any class you define to be part of
mypackage package must be stored in
a directory called mypackage. Additional points about package:
A package is always defined as a separate folder having the same
name as the package name.
Store all the classes in that package folder.
All classes of the package which we wish to access outside the
package must be declared public.
All classes within the package must have the package statement
as its first line.
All classes of the package must be compiled before use (So that
they are error free)
Example of Java packages:
Package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}

How to compile Java packages:


This is just like compiling a normal java program. If you are not
using any IDE, you need to follow the steps given below to
successfully compile your packages:
java -d directory javafilename For example
javac -d . Simple.java

The -d switch specifies the destination where to put the generated


class file. You can use any directory name like /home (in case of
Linux), d:/abc (in case of windows) etc. If you want to keep the
package within the same directory, you can use . (dot).

How to run java package program:


You need to use fully qualified name e.g. mypack.Simple etc to run
the class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple

Output : welcome to package ;


The -d is a switch that tells the compiler where to put the class file
i.e. it represents destination. The . represents the current folder.
How to access package from another package:
There are three ways to access the package from outside the
package.

import package.*;
import package.classname;
fully qualified name.

Using packagename.*:

If you use package.* then all the classes and interfaces of this
package will be accessible but not subpackages.

The import keyword is used to make the classes and interface of


another package accessible to the current package.

Example of package that import the packagename.*:

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

// File: B.java
package mypack;

import pack.*;

class B {
public static void main(String args[]) {
A obj = new A();
obj.msg();
}
}
Output: Hello java

Using packagename.classname:

If you import package.classname then only declared class of this


package will be accessible.
Example of package by import package.classname:
// File: A.java
package pack;

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

// File: B.java
package mypack;

import pack.A;

class B {
public static void main(String args[]) {
A obj = new A();
obj.msg();
}
}
Output: Hello
Using fully qualified name:

If you use fully qualified name then only declared class of this
package will be accessible. Now there is no need to import. But
you need to use fully qualified name every time when you are
accessing the class or interface.

It is generally used when two packages have same class name e.g.
java.util and java.sql packages contain Date class.

Example of package by import fully qualified name:

// File: A.java
package pack;

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

// File: B.java
package mypack;
class B {
public static void main(String args[]) {
pack.A obj = new pack.A(); // using fully qualified name
obj.msg();
}
}
Output : Hello

Note: If you import a package, subpackages will not be imported.


If you import a package, all the classes and interface of that
package will be imported excluding the classes and interfaces of
the subpackages. Hence, you need to import the subpackage as
well.

Subpackage in java:

Package inside the package is called the subpackage. It should be


created to categorize the package further.

Let's take an example, Sun Microsystem has definded a package


named java that contains many classes like System, String, Reader,
Writer, Socket etc. These classes represent a particular group e.g.
Reader and Writer classes are for Input/Output operation, Socket
and ServerSocket classes are for networking etc and so on. So, Sun
has subcategorized the java package into subpackages such as
lang, net, io etc. and put the Input/Output related classes in io
package, Server and ServerSocket classes in net packages and so
on.

package com.javatpoint.core;
class Simple{
public static void main(String args[]){ System.out.println("Hello
subpackage");
}
}
To Compile: javac -d . Simple.java

To Run: java com.javatpoint.core.Simple

Output: Hello subpackage

How to send the class file to another directory or drive:

There is a scenario, I want to put the class file of A.java source file
in classes folder of c: drive.

For example :
// File: Simple.java
package mypack;
public class Simple {
public static void main(String args[]) {
System.out.println("Welcome to package");
}
}
To Compile:
e:\sources> javac -d c:\classes Simple.java
To Run:
To run this program from e:\source directory, you need to set
classpath of the directory where the class file resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple
Another way to run this program by -classpath switch of java:

The -classpath switch can be used with javac and java tool.

To run this program from e:\source directory, you can use -


classpath switch of java that tells where to look for class file. For
example:

e:\sources> java -classpath


c:\classes mypack.Simple

Output: Welcome to package


What is Exception?
1.An exception is an unexpected event, which may occur during the
execution of a program (at run time), to disrupt the normal flow of
the program’s instructions.

2.This leads to the abnormal termination of the program, which is not


always recommended.

3. The exception handling in java is one of the powerful mechanisms


to handle the runtime errors so that normal flow of the application
can be maintained.

Reasons of An exception occur?


Invalid data as input.
Network connection may be disturbed in the middle of
communications
JVM may run out of memory.
File cannot be found/opened.
These exceptions are caused by user error, programmer error, and
physical resources.

Classification of exceptions?

The exceptions can be classified into three categories.


Checked exceptions − A checked exception is an exception that
occurs at the compile time, also called as compile time (static time)
exceptions. These exceptions cannot be ignored at the time of
compilation. So, the programmer should handle these exceptions.

Unchecked exceptions − An unchecked exception is an exception that


occurs at run time, also called as Runtime Exceptions. These include
programming bugs, such as logic errors or improper use of an API.
Runtime exceptions are ignored at the time of compilation.

Errors − Errors are not exceptions, but problems may arise beyond
the control of the user or the programmer. Errors are typically ignored
in your code because you can rarely do anything about an error. For
example, if a stack overflow occurs, an error will arise. They are also
ignored at the time of compilation.

Error v/s Exception:

Error:
An Error indicates serious problem that a reasonable application
should not try to catch.
An Error is a severe situation generated when the user performs an
unexpected operation
Exception:
Exception indicates conditions that a reasonable application might
try to catch.
An Exception is an event that occurs during the program execution
and disrupts the normal flow of the program’s execution
Unchecked v/s Checked-

EXCEPTION HIERARCHY
The java.lang.Exception class is the base class for all exception classes.
All exception and errors types are sub classes of class Throwable,
which is base class of hierarchy.
The Exception class has two main subclasses: IOException class and
RuntimeException class
Exceptions Methods

Method Description
public String Returns a detailed message about
getMessage() the exception that has occurred.
This message is initialized in the
Throwable constructor.
public Throwable Returns the cause of the exception
getCause() as represented by a Throwable
object.
public String Returns the name of the class
toString() concatenated with the re- sult of
getMessage().
public void Prints the result of toString() along
printStackTrace() with the stack trace to System.err,
the error output stream.
public Returns an array containing each
StackTraceElement [] element on the stack trace. The
getStackTrace() element at index 0 represents the
top of the call stack, and the last
element in the array represents the
method at the bottom of the call
stack.
public Throwable Fills the stack trace of this
fillInStackTrace() Throwable object with the current
stack trace, adding to any previous
information in the stack trace.

Exception handling in java uses the following Keywords


try
catch
finally
throw
throws

try {
// block of code to monitor for errors
// the code you think can raise an exception
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ... additional catch blocks for handling different exception types

// optional
finally {
// block of code to be executed after try block ends, whether an
exception occurred or not
}
Throwing and catching exceptions
Catching Exceptions
A method catches an exception using a combination of the try and
catch keywords. The program code that may generate an exception
should be placed inside the try/catch block. The syntax for try/catch
is depicted as below−
Syntax
try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
}

The code which is prone to exceptions is placed in the try block.


When an exception oc- curs, that exception is handled by catch block
associated with it. Every try block should be immediately followed
either by a catch block or finally block.
A catch statement involves declaring the type of exception that might
be tried to catch. If an exception occurs, then the catch block (or
blocks) which follow the try block is checked. If the type of exception
that occurred is listed in a catch block, the exception is passed to the
catch block similar to an argument that is passed into a method
parameter.

class Exception_example {
public static void main(String args[]) {
int a, b;
try {
// Initialize a with a non-zero value
a = 2;
b = 10 / a; // raises the arithmetic exception
System.out.println("Try block.");
} catch (ArithmeticException e) {
// Catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After try/catch block.");
}
}
Output:
Division by zero.
After try/catch block.

Multiple catch Clauses


In some cases, more than one exception could be raised by a single
piece of code. To handle this multiple exceptions, two or more catch
clauses can be specified. Here, each catch block catches different type
of exception. When an exception is thrown, each catch statement is
inspected in order, and the first one whose type matches that of the
exception is executed. After one catch statement executes, the others
are bypassed, and execution continues after the try/catch block. The
following example traps two different exception types:

class MultiCatch_Example {
public static void main(String args[]) {
try {
int a, b;
a = args.length;
System.out.println("a = " + a);
b = 10 / a; // may cause division-by-zero error
int arr[] = {10, 20};
arr[5] = 100;
} catch (ArithmeticException e) {
System.out.println("Divide by 0: " + e);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
Here is the output generated by the execution of the program in both
ways:
C:\>java MultiCatch_Example a = 0
Divide by 0: java.lang.ArithmeticException: / by zero After try/catch
blocks.
C:\>java MultiCatch_Example arg1
a=1
Array index oob: java.lang.ArrayIndexOutOfBoundsException:5
Nested try block
Sometimes a situation may arise where a part of a block may cause
one error and the entire block itself may cause another error. In such
cases, exception handlers have to be nested.

try {
// statement 1;
// statement 2;

try {
// statement 1;
// statement 2;
} catch (Exception e) {
// Handle exception for the inner try block
}

} catch (Exception e) {
// Handle exception for the outer try block
}

// Continue with more try-catch blocks if needed


class Nestedtry_Example {
public static void main(String args[]) {
try {
try {
System.out.println("division");
int a, b;
a = 0;
b = 10 / a;
} catch (ArithmeticException e) {
System.out.println(e);
}

try {
int a[] = new int[5];
a[6] = 3;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}

System.out.println("other statement");
} catch (Exception e) {
System.out.println("handled");
}
System.out.println("normal flow..");
}
}
Throw keyword
The Java throw keyword is used to explicitly throw an exception. The
general form of throw is shown below:
throw ThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a
subclass of Throw- able. Primitive types, such as int or char, as well as
non-Throwable classes, such as String and Object, cannot be used as
exceptions.
There are two ways to obtain a Throwable object:
using a parameter in a catch clause
creating one with the new operator.
The following program explains the use of throw keyword.
public class TestThrow1 {
static void validate(int age) {
try {
if (age < 18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
} catch (ArithmeticException e) {
System.out.println("Caught inside ArithmeticException.");
throw e; // rethrow the exception
}
}

public static void main(String args[]) {


try {
validate(13);
} catch (ArithmeticException e) {
System.out.println("Recaught ArithmeticException.");
}
}
}
The flow of execution stops immediately after the throw statement
and any subsequent statements that are not executed. The nearest
enclosing try block is inspected to see if it has a catch statement that
matches the type of exception. If it does find a match, control is
trans- ferred to that statement. If not, then the next enclosing try
statement is inspected, and so on. If no matching catch is found, then
the default exception handler halts the program and prints the stack
trace.

The Throws/Throw Keywords:

If a method does not handle a checked exception, the method must


be declared using the throws keyword. The throws keyword appears
at the end of a method’s signature.
The difference between throws and throw keywords is that, throws is
used to postpone the handling of a checked exception and throw is
used to invoke an exception explicitly.
The following method declares that it throws a Remote Exception −
Example
import java.io.*;
public class throw_Example1 {
public void function(int a) throws RemoteException {
// Method implementation throw new RemoteException();
} // Remainder of class definition
}

A method can declare that it throws more than one exception, in


which case the excep- tions are declared in a list separated by
commas. For example, the following method declares that it throws a
RemoteException and an ArithmeticException .

import java.io.*;
public class throw_Example2 {
public void function(int a) throws
RemoteException,ArithmeticException {
// Method implementation
}
// Remainder of class definition
}

The Finally Block


The finally block follows a try block or a catch block. A finally block of
code always ex- ecutes, irrespective of the occurrence of an Exception.
A finally block appears at the end of the catch blocks that follows the
below syntax.
Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
}
finally {
// The finally block always executes.
}

Example
public class Finally_Example {
public static void main(String args[]) {
try {

int a,b;
a=0;
b=10/a;
} catch (ArithmeticException e) { System.out.println(“Exception thrown
:” + e);
}finally {
System.out.println(“The finally block is executed”);
}
}
}

Points to remember:
A catch clause cannot exist without a try statement.
It is not compulsory to have finally clauses whenever a try/catch block
is present.
The try block cannot be present without either catch clause or finally
clause.
Any code cannot be present in between the try, catch, finally blocks.
USER DEFINED EXCEPTION IN JAVA
In Java, we can create our own exceptions that are derived classes of
the Exception class. Creating our own Exception is known as custom
exception or user-defined exception. Basically, Java custom
exceptions are used to customize the exception according to user
need.
Consider the example 1 in which InvalidAgeException class extends
the Exception class.
Using the custom exception, we can have your own exception and
message. Here, we have passed a string to the constructor of
superclass i.e. Exception class that can be obtained using
getMessage() method on the object we have created.
Syntax:
class User_defined_name extends Exception{
………..
}

Why use custom exceptions?


Java exceptions cover almost all the general type of exceptions that
may occur in the programming. However, we sometimes need to
create custom exceptions.
Following are few of the reasons to use custom exceptions:
To catch and provide specific treatment to a subset of existing Java
exceptions.
Business logic exceptions: These are the exceptions related to
business logic and workflow. It is useful for the application users or
the developers to understand the exact problem.
Example of custom exception :
TestCustomException1.java
// class representing custom exception
class InvalidAgeException extends Exception
{
public InvalidAgeException (String str)
{
// calling the constructor of parent Exception
super(str);
}
}

// class that uses custom exception InvalidAgeException


public class TestCustomException1
{
// method to check the age
static void validate (int age) throws InvalidAgeException{
if(age < 18){

// throw an object of user defined exception


throw new InvalidAgeException("age is not valid to vote");
}
else {
System.out.println("welcome to vote");
}
}

// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");
// printing the message from InvalidAgeException object
System.out.println("Exception occured: " + ex);
}

System.out.println("rest of the code...");


}
}
Output:

Unit 3 end here


UNIT – 4 – JAVA
File I/o

• File I/o or file handling defines that we can read and write data on
a file of java IO –Package contain all the class through which we can
perform Input/Ouput Operation in file .

• The File I/O uses the concept of stream to make I/O operation fast.
• Stream:- the stream is sequence of data on the on the basis of
java .io Package

• Stream :-
I/P Stream –System.in
O/P Stream-System.out
Error Stream-System.err
File handling Method
1. CanRead()
2. CanWrite()
3. CreateNewFile()
4. Delete()
5. Exists()
6. Length()
7. GetName()
8. getAbsolutepath()
9. Mddir()
10. List()
11. Read()
12.Write()
13.renameTo()
File handling Classes
1. File
2. FileReader
3. FileWriter
4. FileInputStream
5. FileOutputStream
6. BufferedInputStream
7. BufferedOutputStream
Operation on file:
1. Create File
2. Get file information
3. Read File
4. Wite File
Create File :To create a file in Java, you can use the
createNewFile() method. This method returns a boolean
value: true if the file was successfully created, and false if the
file already exists.

Create File with try -catch


import java.io.*;
public class createFile
{ public static void main(String args[])
{ File f=new File("C:\\Users\\HOME\\Desktop\\ lc.txt"); try
{ if(f.createNewFile())
{ System.out.println("file Successfully Create...!"); } else
{ System.out.println("File already exist"); }}
catch (IOException i)
{ System.out.println("exception handled "); }}
}

Create File with Throw (bypassing try-catch)


import java.io.*;
public class fileinfo
{
public static void main(String args[]) throws IOException
{ File f=new File("C:\\Users\\HOME\\Desktop\\ lc.txt");

if(f.createNewFile())
{ System.out.println("file Successfully Create...!"); }
else
{ System.out.println("File already exist"); }
}
}
}

Get file information:

import java.io.*;
public class fileinfo
{
public static void main(String args[]) throws IOException
{ File f=new File("C:\\Users\\HOME\\Desktop\\ lc.txt");

if(f.exist ())
{ System.out.println(“File Name:“+getName()); }

else
{ System.out.println("File Doesn’t exist"); }
}
}
}
Input Stream Class:

• Input Stream:
• The Java InputStream class is the superclass of all input
streams. The input stream is used to read data from
numerous input devices like the keyboard, network, etc.
InputStream is an abstract class, and because of this, it is
not useful by itself. However, its subclasses are used to
read data.
• Java FileInputStream example 1: read single character
Example

import java.io.FileInputStream;

public class DataStreamExample {


public static void main(String args[]) {
try {
FileInputStream fin = new FileInputStream("D:\\
testout.txt");
int i = fin.read();
System.out.print((char)i);
fin.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
output: Welcome to javatpoint

Java FileInputStream class methods:


Exampe of input class :
public class InputStreamReader Example {
public static void main(String[] args) {
try {
InputStream stream = new FileInputStream("file.txt"
);
Reader reader = new InputStreamReader(stream);
int data = reader.read();
while (data != -1) {
System.out.print((char) data);
data = reader.read();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Out Put :I love my country

Output Stream and Classes


• The output stream is used to write data to numerous
output devices like the monitor, file, etc. OutputStream is
an abstract superclass that represents an output stream.
OutputStream is an abstract class and because of this, it
is not useful by itself. However, its subclasses are used to
write data.
• There are several subclasses of the OutputStream class
which are as follows:
• ByteArrayOutputStream
• FileOutputStream
• StringBufferOutputStream
• ObjectOutputStream
• DataOutputStream
• PrintStream

Output Stream and Classes


Creating an OutputStream
// Syntax
OutputStream obj = new FileOutputStream();S.
1.write(): Writes the specified byte to the output stream.
2.write(byte[] array): Writes the bytes which are inside a
specific array to the output stream.
3.close() :-Closes the output stream.
4.flush():-Forces to write all the data present in an output
stream to the destination.

Java FileOutputStream Example 1: write byte

import java.io.FileOutputStream;

public class FileOutputStreamExample {


public static void main(String args[]) {
try {
FileOutputStream fout = new FileOutputStream("D:\\
testout.txt");
fout.write(65);
fout.close();
System.out.println("Success...");
} catch (Exception e) {
System.out.println(e);
}
}
}
Output: Success...
A

Java FileOutputStream example 2: write string

import java.io.FileOutputStream;

public class FileOutputStreamExample {


public static void main(String args[]) {
try {
FileOutputStream fout = new
FileOutputStream("D:\\testout.txt");
String s = "Welcome to Java";
byte b[] = s.getBytes(); // Converting string into
byte array
fout.write(b);
fout.close();
System.out.println("Success...");
} catch (Exception e) {
System.out.println(e);
}
}
}

output:Success...
Welcome to java.

RandomAccessFile in Java

• RandomAccessFile in Java is a class that allows data to


be read from and written to at any location in the file.
• In other simple words, RandomAccessFile class allows
creating files that can be used for reading and writing
data with random access.
• Random access means access to stored data in any order
that the user desires. That is, we can access data in the
file in any order while using the file. Such a file is known
as random access file.
• A random-access file is a file that can be used for both
reading and writing using RandomAccessFile class in
java.
Why RandomAccessFile Class in Java?
• So far we have discussed all I/O streams that can be used
either for “read only” or for “write only” operations and
not for both purposes simultaneously.
• That is, all of the I/O streams we have used so far are
known as read-only or write-only streams. These streams
are called sequential streams in Java.
• A file that is read or written using a sequential stream is
called a sequential-access file. The data of a sequential-
access file cannot be updated.
• So, for reading and writing data simultaneously, Java
provides the RandomAccessFile class. Using random
access file class, we can change the location in the file at
which the next read or write operation will occur.
RandomAccessFile Methods in Java
1. void close(): This method closes the random access file
stream and releases any system resources associated
with the stream.
2. FileChannel getChannel() :This method returns the
unique FileChannel object associated with the file.
3. FileDescriptor getFD():This method returns the opaque file
descriptor object associated with the underlying stream.
4. long getFilePointer():This method returns the current offset
(in bytes) from the beginning of the file to where the next
read or write occurs.
5. long length():This method returns the length (number of
bytes) of this file.
6. int read():It reads a byte of data from this file and returns –
1 at the end of the stream.
7. int read(byte[ ] b):It reads up to b.length bytes of data from
this file into an array of bytes.

Applet
 Applet is java program that can be embedded into html
pages.
 Applets transported over the internet form one
computer to another and run
using applet viewer or can run on any java enabled
web browser using JVM.
 An applet is a small program that is intended not to be
run on its own, but
rather to be embedded inside another application.
 The applet class provides a standard interface between
applet and their environment

Advantages of applet

 It provides GUI, facilitates graphics animation and


multimedia.
 Avoids risk and provide 2 way interactions between
webpages.
 Applets can work on all versions of Java plugin

disadvantages of applet
 Java applets requires JVM so first time it takes significant
startup time.
 It is difficult to design and build good user interface in
applet as compare to html technology.
 Some organization only allowed software installed by
administrator, As a result many users cannot view applet
by default.

Types of Applets:

. Local Applets
 An applet developed locally and stored in a local system
is known as a local applet.
 When a web page is trying to find a local applet, it does
not need to use the internet and therefore the local
system does not require the internet
connection.
 It simply searches the directories in the local system;
locates and loads the specified applet

Remote Applet:
 A remote applet is that which is developed by someone
else and stored on a remote computer connected to the
internet. If our system is connected to the internet, we
can download the remote applet into our system via at
the internet and run it.
 Your browser must, of course, be connected to the
Internet at the time it needs to display the remote
applet.
 For locate and load a remote applet, we must know the
applet’s address on the web. This address is known as
Uniform Resource Location (URL)
Applet/Application:

1. Applet does not use main() method for initiating


execution of code.
Application use main() method for initiating
execution of code .
2. Applet cannot run independently
Application can run independently
3. Applet cannot read from or write to files in local
computer
Application can read from or write to files in local
computer.
4. Applet cannot communicate with other servers on
network .
Application can communicate with other servers on
network .
5. Applet cannot run any program from local computer .
Application can run any program from local computer.
6. Applet are restricted from using libraries from other
language such asC or C++
Application are not restricted fromusing libraries from
other language
7. Applets are event driven
Applications are control driven.

Methods of Applet Life Cycle


Methods of Applet Life Cycle
• init(): The init() method is the first method to run that
initializes the applet. It can be invoked only once at the
time of initialization. The web browser creates the
initialized objects, i.e., the web browser (after checking
the security settings) runs the init() method within the
applet.
• start(): The start() method contains the actual code of
the applet and starts the applet. It is invoked
immediately after the init() method is invoked. Every
time the browser is loaded or refreshed, the start()
method is invoked. It is also invoked whenever the
applet is maximized, restored, or moving from one tab
to another in the browser. It is in an inactive state until
the init() method is invoked.

• stop(): The stop() method stops the execution of the


applet. The stop () method is invoked whenever the
applet is stopped, minimized, or moving from one tab to
another in the browser, the stop() method is invoked.
When we go back to that page, the start() method is
invoked again.
• destroy(): The destroy() method destroys the applet after
its work is done. It is invoked when the applet window is
closed or when the tab containing the webpage is
closed. It removes the applet object from memory and is
executed only once. We cannot start the applet once it is
destroyed.
• paint(): The paint() method belongs to the Graphics class
in Java. It is used to draw shapes like circle, square,
trapezium, etc., in the applet. It is executed after the
start() method and when the browser or applet windows
are resized.

Write a simple applet which display message ‘Welcome to


Java’.

import java. applet.*;


import java.awt.*;
public class WelcomeJava extends Applet
{
public void paint( Graphics g)
{
g.drawString(“Welcome to java”,25,50);
}
}

Example of Graphics in applet:


import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet{

public void paint(Graphics g){


g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);

`}
}

You might also like