Sei sulla pagina 1di 42

II YEAR / IV SEMESTER

(ELECTRICAL AND ELECTRONICS ENGINEERING)


CS6456 - OBJECT ORIENTED PROGRAMMING
UNIT - V
EXCEPTION HANDLING

PREPARED BY
S.NARMADHA M.E., (AP/CSE)
VERIFIED BY

HOD

PRINCIPAL

CORRESPONDENT

DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING


SENGUNTHAR COLLEGE OF ENGINEERING TIRUCHENGODE
1

UNIT V
EXCEPTION HANDLING

Packages and Interfaces


Exception handling
Multithreaded programming
Strings
Input/Output

LIST OF IMPORTANT QUESTIONS


UNIT V

EXCEPTION HANDLING
PART-A
1. What is an interface? [A/M2015] [M/J2012] [or] Define the term interface. Write the
general form of Interface. [M/J2014] [or] How interface is used in java? Give an
example. [N/D2014] [or] What is meant by Interface in Java? [M/J2013][N/D2013]
2. Write short note on throw().[A/M2015]
3. What is an exception in java? [N/D2014]
4. When will you use Multi-threaded programming? [M/J2013] [N/D2013]
5. What is Package? [M/J2012] [or] Define a package in Java. How it is created?
[N/D2012]
6. Write the syntax for concatenating two strings. [N/D2012]
7. What is meant by stringBuffer? [A/M2011]
8. What is the difference between throw and throws clause?
9. List the various Thread Methods.
10. What are checked and unchecked Exceptions?
11. What is multithreading? [M/J2016]
12. Distinguish between interface and class. [M/J2016]

PART-B
1. Illustrate the use of try-catch clauses by sample statements of rare type run time
error. (16m) [A/M2015] [N/D2011][N/D2013]
2. What is multi threading? Write a multi threaded program in java and explain. (16m)
[A/M2015]
[or]
Discuss with examples for creating multiple threads. (16m) [M/J2014] [or] What is a
Thread? What are the different states of Thread? Explain the creation of Thread with an
example program. (16m) [N/D2014] [N/D2012] [or] What is thread? Explain the life

cycle of a thread with neat diagram and discuss the important methods in the thread
class that are commonly used in application. (8m) [M/J2012] [N/D2011]
3. With suitable examples, explain packages in detail. (16m) [M/J2014] [or] Explain
about Packages in Java with an example program. List built in Java API packages.
(16m) [N/D2014] (16m) [M/J2013] [N/D2012][N/D2013]
4. Discuss about Strings with programming examples. (16m) [M/J2013]
5. Explain the various forms of interface implementations. (8m) [M/J2012] [N/D2011]
[N/D2012]
6. How do you define an interface? Why do the members of interface are static and
final? [M/J2016] [7m]
7. Write a java program to implement nested packages.
8. Distinguish between arrays and strings .[M/J2016] [3m]
9. Explain the method available in the String Bufferf class.[M/J2016] [5m]
10. Explain the use of command line arguments with an example. [M/J2016] [8m]

NOTES
UNIT V
EXCEPTION HANDLING

PART A

1. What is an interface? [A/M2015] [M/J2012] [or] Define the term interface. Write
the general form of Interface. [M/J2014] [or] How interface is used in java? Give
an example. [N/D2014] [or] What is meant by Interface in Java? [M/J2013]
[N/D2013]
An interface is a reference type in Java, it is similar to class, it is a collection of
abstract methods. A class implements an interface, thereby inheriting the abstract
methods of the interface. The interface keyword is used to declare an interface. There
are mainly three reasons to use interface. They are given below.

It is used to achieve fully abstraction.

By interface, we can support the functionality of multiple inheritance.

It can be used to achieve loose coupling.

Example:
5

public interface NameOfInterface


{
---}
2. Write short note on throw().[A/M2015]
The Java throws keyword is used to declare an exception. It gives an
information to the programmer that there may occur an exception so it is better for the
programmer to provide the exception handling code so that normal flow can be
maintained.

Syntax:
return_type method_name() throws exception_class_name
{
//method code
}
3. What is an exception in java? [N/D2014]
An exception (or exceptional event) is a problem that arises during the execution
of a program. When an Exception occurs the normal flow of the program is disrupted
and the program/Application terminates abnormally, which is not recommended,
therefore these exceptions are to be handled.
4. When will you use Multi-threaded programming? [M/J2013] [N/D2013]
Java is amulti threaded programming language which means we can develop
multi threaded program using Java. A multi threaded program contains two or more
parts that can run concurrently and each part can handle different task at the same time
making optimal use of the available resources specially when your computer has
multiple CPUs.

5. What is Package? [M/J2012] [or] Define a package in Java. How it is created?


[N/D2012]
A Package can be defined as a grouping of related types (classes, interfaces,
enumerations and annotations ) providing access protection and name space
management. Packages are used in Java in order to prevent naming conflicts, to control
access, to make searching/locating of specific resources.
Some of the existing packages in Java are:

java.lang - bundles the fundamental classes

java.io - classes for input , output functions are bundled in this package

6.Write the syntax for concatenating two strings. [N/D2012]


Concatenates the specified string to the end of this string.
Syntax: String concat(String str)
Example:
public class Test {
public static void main(String args[]) {
String s = "Strings are immutable";
s = s.concat(" all the time");
System.out.println(s);
}
}
7. What is meant by stringBuffer? [A/M2011]
The StringBuffer class is used when there is a necessity to make a lot of
modifications to Strings of characters.

Example:
public class Test{

Output:

public static void main(String args[]){

test String Buffer

StringBuffer sBuffer = new


StringBuffer(" test");
sBuffer.append(" String Buffer");
System.out.println(sBuffer);
}
}

8. What is the difference between throw and throws clause?


Throw is used to throw an exception manually, where as throws is used in the
case of checked exceptions, to tell the compiler that we haven't handled the exception,
so that the exception will be handled by the calling function
9. List the various Thread Methods.

suspend()
resume ()
wait()
notify()
notifyAll()
join()
isAlive()

10. What are checked and unchecked Exceptions ?


Unchecked Exceptions are those which are not included in throws list and are
derived from Runtime Exception which are automatically available and are in java.lang.
Checked Exceptions are those which cannot handle by itself.
11. What is multithreading? [M/J2016]

Multithreading in java is a process of executing multiple threads simultaneously. Thread


is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing
and multithreading, both are used to achieve multitasking.
12. Distinguish between interface and class. [M/J2016]
A Class can be instantiated but an Interface cannot be instantiated You can create an
instance of an Object that implements the Interface. A Class is a full body entity with
members, methods along with there definition and implementation.

13. What are the various states and methods of thread ?


States : Running, Ready to run, Suspended, Resumed, blocked and terminated.
Methods : getName, getPriority, isAlive, join, run, sleep, start.
14.What is Stream? What are the two types of Java Stream.
In Java, the I/O abstractions are called streams. Stream is flow of data between
sources. Java defines two types of streams
1

Character Stream Human Readable data

Byte Stream Machine formatted data

15. What are the various types of i/o streams available in java
1

Byte Stream Machine formatted data

Character Stream Human Readable data

Buffered stream

16. What is an I/O stream?


An I/O Stream represents an input source or an output destination. A stream can
represent many different kinds of sources and destinations, including disk files, devices,
other programs, and memory arrays.
9

Streams support many different kinds of data, including simple bytes, primitive data
types, localized characters, and objects. Some streams simply pass on data; others
manipulate and transform the data in useful ways.

A stream is a sequence of data. A program uses an input stream to read data


from a source, one item at a time.

A program uses an output stream to write data to a destination, one item at time.
PART - B

1. Illustrate the use of try-catch clauses by sample statements of rare type run
time error. (16m) [A/M2015] [N/D2011][N/D2013]
Sometimes exceptions are caused by user error, others by programmer error,
and others by physical resources that have failed in some manner. The three categories
of exceptions,
Checked exceptions: A checked exception is an exception that is typically a user
error or a problem that cannot be foreseen by the programmer. For example, if a file is
to be opened, but the file cannot be found, an exception occurs. These exceptions
cannot simply be ignored at the time of compilation.
Runtime exceptions: A runtime exception is an exception that occurs that probably
could have been avoided by the programmer. As opposed to checked exceptions,
runtime exceptions are ignored at the time of compliation.
Errors: These are not exceptions at all, but problems that arise beyond the control of
the user or the programmer. Errors are typically ignored in 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.
Java Exceptions
The mechanism suggests incorporation of a separate error handling code
mat performs the following tasks:
1. Find the problem [Hit the exception},
2. Inform that an error has occurred {Throw the exception)
10

3. Receive the error information {Catch the exception)


4. Take corrective actions {Handle the exception)
Catching Exceptions
A method catches an exception using a combination of the try and catch
keywords. A try/catch block is placed around the code that might generate an exception.
Code within a try/catch block is referred to as protected code.
Syntax :
try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}
A catch statement involves declaring the type of exception you are trying to
catch. If an exception occurs in protected code, the catch block (or blocks) that follows
the try is checked. If the type of exception that occurred is listed in a catch block, the
exception is passed to the catch block much as an argument is passed into a method
parameter.
Example:
import java.io.*;
public class ExcepTest{
public static void main(String args[]){
try{
int a[] = new int[2];
System.out.println("Access
element three :" + a[3]);
}
catch(ArrayIndexOutOfBoundsException
e){
System.out.println("Exception
thrown :" + e);
}

System.out.println("Out of the block");


}
}

Output:
Exception thrown
:java.lang.ArrayIndexOutOfBoundsException
:3
Out of the block

11

Multiple catch Blocks:


A try block can be followed by multiple catch blocks.
Syntax:

Example:

try

try

{
//Protected code

file = new FileInputStream(fileName);

}catch(ExceptionType1 e1)
{

x = (byte) file.read();
}catch(IOException i)

//Catch block

}catch(ExceptionType2 e2)

i.printStackTrace();

return -1;
//Catch block

}catch(FileNotFoundException

}catch(ExceptionType3 e3)

valid!

{
//Catch block

f)

//Not

f.printStackTrace();

return -1;
}
The previous statements demonstrate three catch blocks, but you can have any

number of them after a single try. If an exception occurs in the protected code, the
exception is thrown to the first catch block in the list.
If the data type of the exception thrown matches ExceptionType1, it gets caught
there. If not, the exception passes down to the second catch statement. This continues
until the exception either is caught or falls through all catches, in which case the current
method stops execution and the exception is thrown down to the previous method on
the call stack.
The throws/throw Keywords:
If a method does not handle a checked exception, the method must declare it
using the throws keyword. The throws keyword appears at the end of a method's
signature.
12

You can throw an exception, either a newly instantiated one or an exception that you
just caught, by using the throw keyword. Try to understand the different in throws and
throw keywords.
The following method declares that it

The following method declares that it

throws a RemoteException:

throws a RemoteException and an


InsufficientFundsException:

import java.io.*;
public class className
{
public void deposit(double amount)
throws RemoteException
{
// Method implementation
throw new RemoteException();
}
//Remainder of class definition
}

import java.io.*;
public class className
{
public void withdraw(double amount)
throws RemoteException,
InsufficientFundsException
{
// Method implementation
}
//Remainder of class definition
}

The finally Keyword:


The finally keyword is used to create a block of code that follows a try block. A
finally block of code always executes, whether or not an exception has occurred. Using
a finally block allows you to run any cleanup-type statements that you want to execute,
no matter what happens in the protected code.
Syntax:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block

Example:
public class ExcepTest{
public static void main(String args[]){
int a[] = new int[2];
try{
System.out.println("Access element
three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException
e){
System.out.println("Exception thrown :"
13

}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}

+ e);
}
finally{
a[0] = 6;
System.out.println("First element value:
" +a[0]);
System.out.println("The finally
statement is executed");
}
}
}
Output:
Exception thrown
:java.lang.ArrayIndexOutOfBoundsException
:3
First element value: 6

A catch clause cannot exist without a try statement.


It is not compulsory to have finally clauses when ever 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.

Declaring our own Exception[creating own Exceptions]


Involves following points in mind when writing our own exception classes,

All exceptions must be a child of Throwable.


If you want to write a checked exception that is automatically enforced by the

Handle or Declare Rule, you need to extend the Exception class.


If you want to write a runtime exception, you need to extend the
RuntimeException class.

We can define our own Exception class as below:


class MyException extends Exception
{ .
}
We just need to extend the Exception class to create your own Exception class.
These

are

considered

to

be

checked
14

exceptions.

The

following

InsufficientFundsException class is a user-defined exception that extends the Exception


class, making it a checked exception. An exception class is like any other class,
containing useful fields and methods.
Example:
// File Name InsufficientFundsException.java
import java.io.*;
public class InsufficientFundsException extends Exception
{
private double amount;
public InsufficientFundsException(double amount)
{
this.amount = amount;
}
public double getAmount()
{
return amount;
}
}
To demonstrate using our user-defined exception, the following CheckingAccount class
contains a withdraw() method that throws an InsufficientFundsException.
Program 1:
// File Name CheckingAccount.java
import java.io.*;
public class CheckingAccount
{
private double balance;
private int number;
public CheckingAccount(int number)
{
this.number = number;
}
public void deposit(double amount)
{
balance += amount;
}
public void withdraw(double amount)
throws

Program 2:
// File Name BankDemo.java
public class BankDemo
{
public static void main(String [] args)
{
CheckingAccount c = new
CheckingAccount(101);
System.out.println("Depositing
$500...");
c.deposit(500.00);
try
{
System.out.println("\nWithdrawing
$100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing
15

$600...");
c.withdraw(600.00);
}catch(InsufficientFundsException e)
{
System.out.println("Sorry, but you
are short $"
+ e.getAmount());
e.printStackTrace();
}
}
}

InsufficientFundsException
{
if(amount <= balance)
{
balance = amount;
}
else
{
double needs = amount - balance;
throw new
InsufficientFundsException(needs);
}
}
public double getBalance()
{
return balance;
}
public int getNumber()
{
return number;
}
}
The above BankDemo program 2 demonstrates invoking the deposit() and withdraw()
methods of CheckingAccount.
Compile all the above three files and run BankDemo, this would produce following
result:
Depositing $500...
Withdrawing $100...
Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)
2. What is multi threading? Write a multi threaded program in java and explain.
(16m)[A/M2015]
16

[or]
Discuss with examples for creating multiple threads. (16m) [M/J2014] [or] What is
a Thread? What are the different states of Thread? Explain the creation of Thread
with an example program. (16m) [N/D2014] [N/D2012] [or] What is thread?
Explain the life cycle of a thread with neat diagram and discuss the important
methods in the thread class that are commonly used in application. (8m)
[M/J2012] [N/D2011]
A thread is an independent path of execution within a program. Many threads can
run concurrently within a program. Every thread in Java is created and controlled by
the java.lang.Thread class. A Java program can have many threads, and these threads
can run concurrently, either asynchronously or synchronously.
Java is a multi threaded programming language which means we can develop
multi threaded program using Java. A multi threaded program contains two or more
parts that can run concurrently and each part can handle different task at the same time
making optimal use of the available resources specially when your computer has
multiple CPUs.
Multi threading enables you to write in a way where multiple activities can
proceed concurrently in the same program.
Life Cycle of a Thread:
A thread goes through various stages in its life cycle. For example, a thread is
born, started, runs, and then dies. Following diagram shows complete life cycle of a
thread.

New: A new thread begins its life cycle in the new state. It remains in this state
until the program starts the thread. It is also referred to as a born thread.

Runnable: After a newly born thread is started, the thread becomes runnable. A
thread in this state is considered to be executing its task.

17

Waiting: Sometimes, a thread transitions to the waiting state while the thread
waits for another thread to perform a task.A thread transitions back to the
runnable state only when another thread signals the waiting thread to continue
executing.

Timed waiting: A runnable thread can enter the timed waiting state for a
specified interval of time. A thread in this state transitions back to the runnable
state when that time interval expires or when the event it is waiting for occurs.

Terminated ( Dead ): A runnable thread enters the terminated state when it


completes its task or otherwise terminates.

Thread Priorities:
Every Java thread has a priority that helps the operating system determine the
order in which threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1)
and MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be
allocated processor time before lower-priority threads.
18

Creating threads
Java's creators have graciously designed two ways of creating threads:
implementing an interface and extending a class.

Create Thread by Implementing Runnable Interface:


If your class is intended to be executed as a thread then you can achieve this by
implementing Runnable interface. You will need to follow three basic steps:
Step 1:
The first step is to implement a run() method provided by Runnable interface. This
method provides entry point for the thread and you will put you complete business logic
inside this method. Following is simple syntax of run() method:

public void run( )

Step 2:
At second step you will instantiate a Thread object using the following constructor:

Thread(Runnable threadObj, String threadName);

Where, threadObj is an instance of a class that implements the Runnable interface and
threadName is the name given to the new thread.
Step 3:
Once Thread object is created, you can start it by calling start( ) method, which
executes a call to run( ) method. Following is simple syntax of start() method:

void start( );

19

Example:

Output:

class Multi3 implements Runnable{

thread is running...

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();
}
}
Create Thread by Extending Thread Class:
The second way to create a thread is to create a new class that extends Thread
class using the following two simple steps. This approach provides more flexibility in
handling multiple threads created using available methods in Thread class.
Step 1:
You will need to override run( ) method available in Thread class. This method
provides entry point for the thread and you will put you complete business logic inside
this method. Following is simple syntax of run() method:

public void run( )

Step 2:
Once Thread object is created, you can start it by calling start( ) method, which
executes a call to run( ) method. Following is simple syntax of start() method:

void start( );

Example:

Output:
20

class Multi extends Thread{

thread is running...

public void run(){


System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}

Thread Methods:
Following is the list of important methods available in the Thread class.

21

22

The previous methods are invoked on a particular Thread object. The following methods
in the Thread class are static. Invoking one of the static methods performs the operation
on the currently running thread.

Exception handling in Java threads


public class MyRunnable implements Runnable {
public void run() {
try {
...
} catch (Throwable e) {
log.error("OMFG WTF?!");
}
}
}
23

3. With suitable examples, explain packages in detail. (16m) [M/J2014] [or]


Explain about Packages in Java with an example program. List built in Java API
packages. (16m) [N/D2014] (16m) [M/J2013] [N/D2012][N/D2013]
Packages
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.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc. The

package keyword is used to create a package in java.


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.

24

//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to access package from another package
There are three ways to access the package from outside the package.
1) import package.*;
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.
//save by A.java
package pack;
public class A{
public void msg()
{System.out.println("Hello");}
}
//save by B.java

Output:
Hello

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

25

2) import package.classname;
If you import package.classname then only declared class of this package
will be accessible.
//save by A.java

Output:

package pack;

Hello

public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
3) 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.

26

//save by A.java

Output:

package pack;

Hello

public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
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.
//in the Circle.java file
package graphics;
public class Circle extends Graphic
implements Draggable {
...
}
//in the Rectangle.java file
package graphics;
public class Rectangle extends Graphic
implements Draggable {
27

...
}

4. Discuss about Strings with programming examples. (16m) [M/J2013]


Strings, which are widely used in Java programming, are a sequence of
characters. In the Java programming language, strings are objects. The Java platform
provides the String class to create and manipulate strings.
Creating Strings:
The most direct way to create a string is to write:
String greeting = "Hello world!";
Whenever it encounters a string literal in the code, the compiler creates a String
object with its value in this case, "Hello world!'.
As with any other object, you can create String objects by using the new keyword
and a constructor. The String class has eleven constructors that allow you to provide the
initial value of the string using different sources, such as an array of characters.

public class StringDemo{


Output:

public static void main(String args[]){


char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
String

helloString

hello.

new

String(helloArray);
System.out.println( helloString );
}
}
28

String Length:
The length() method, returns the number of characters contained in the string object.
Below given program is an example of length() , method String class.
Example:
Output:

public class StringDemo {


public static void main(String args[]) {

String Length is : 17

String palindrome = "Dot saw I was


Tod";
int len = palindrome.length();
System.out.println( "String Length is : "
+ len );
}
}
Concatenating Strings:
The String class includes a method for concatenating two strings:
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end. You can also
use the concat() method with string literals, as in:
"My name is ".concat("Zara");
Strings are more commonly concatenated with the + operator, as in:
"Hello," + " world" + "!"
which results in:
"Hello, world!"
Let us look at the following example:

29

Example:

Output:

public class StringDemo {

Dot saw I was Tod

public static void main(String args[]) {


String string1 = "saw I was ";
System.out.println("Dot " + string1 +
"Tod");
}
}

String Methods:
Here is the list of methods supported by String class:
Method
char charAt(int index)
int compareTo(Object o)

int compareTo(String anotherString)


int compareToIgnoreCase(String str)
String concat(String str)
boolean contentEquals(StringBuffer
sb)
boolean endsWith(String suffix)
int hashCode()

int lastIndexOf(int ch)


int length()
String replace(char oldChar, char
newChar)
boolean startsWith(String prefix)

Description
Returns the character at the specified index.
Compares this String to another Object.
Compares two strings lexicographically.
Compares two strings lexicographically,
ignoring case differences.
Concatenates the specified string to the end of
this string.
Returns true if and only if this String represents
the same sequence of characters as the
specified StringBuffer.
Tests if this string ends with the specified
suffix.
Returns a hash code for this string.
Returns the index within this string of the last
occurrence of the specified character.
Returns the length of this string.
Returns a new string resulting from replacing
all occurrences of oldChar in this string with
newChar.
Tests if this string starts with the specified
prefix.
30

5. Explain the various forms of interface implementations. (8m) [M/J2012]


[N/D2011] [N/D2012]
An interface is a reference type in Java, it is similar to class, it is a collection of
abstract methods. A class implements an interface, thereby inheriting the abstract
methods of the interface.
Along with abstract methods an interface may also contain constants, default
methods, static methods, and nested types. Method bodies exist only for default
methods and static methods.
Writing an interface is similar to writing a class. But a class describes the
attributes and behaviors of an object. And an interface contains behaviors that a class
implements.
Unless the class that implements the interface is abstract, all the methods of the
interface need to be defined in the class.
An interface is similar to a class in the following ways:

An interface can contain any number of methods.

An interface is written in a file with a .java extension, with the name of the
interface matching the name of the file.

The byte code of an interface appears in a .class file.

31

Interfaces appear in packages, and their corresponding bytecode file must be in


a directory structure that matches the package name.

However, an interface is different from a class in several ways, including:

It cannot instantiate an interface.

An interface does not contain any constructors.

All of the methods in an interface are abstract.

An interface cannot contain instance fields. The only fields that can appear in an
interface must be declared both static and final.

An interface is not extended by a class; it is implemented by a class.

An interface can extend multiple interfaces.

Declaring Interfaces:
The interface keyword is used to declare an interface. Here is a simple example
to declare an interface:
Example:
Below given is an example of an interface:
/* File name : NameOfInterface.java */
import java.lang.*;
//Any number of import statements
public interface NameOfInterface
{
//Any number of final, static fields
//Any number of abstract method declarations\
32

}
Interfaces have the following properties:

An interface is implicitly abstract. You do not need to use the abstract keyword
while declaring an interface.

Each method in an interface is also implicitly abstract, so the abstract keyword is


not needed.

Methods in an interface are implicitly public.

Example:
/* File name : Animal.java */
interface Animal {
public void eat();
public void travel();
}
Implementing Interfaces:
When a class implements an interface, you can think of the class as signing a
contract, agreeing to perform the specific behaviors of the interface. If a class does not
perform all the behaviors of the interface, the class must declare itself as abstract.
A class uses the implements keyword to implement an interface. The
implements keyword appears in the class declaration following the extends portion of
the declaration.
Output
Example

Mammal eats
Mammal travels

/* File name : MammalInt.java */

33

public class MammalInt implements Animal{


public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels");
}
public int noOfLegs(){
return 0;
}
public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}

When overriding methods defined in interfaces there are several rules to be followed:

Checked exceptions should not be declared on implementation methods other


than the ones declared by the interface method or subclasses of those declared
by the interface method.

The signature of the interface method and the same return type or subtype
should be maintained when overriding the methods.

An implementation class itself can be abstract and if so interface methods need


not be implemented.
34

When implementation interfaces there are several rules:

A class can implement more than one interface at a time.

A class can extend only one class, but implement many interfaces.

An interface can extend another interface, similarly to the way that a class can
extend another class.

Extending Interfaces:
An interface can extend another interface, similarly to the way that a class can
extend another class. The extends keyword is used to extend an interface, and the
child interface inherits the methods of the parent interface.
The following Sports interface is extended by Hockey and Football interfaces.
//Filename: Sports.java
public interface Sports
{
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
//Filename: Football.java
public interface Football extends Sports
{
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
//Filename: Hockey.java
public interface Hockey extends Sports
35

{
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}
The Hockey interface has four methods, but it inherits two from Sports; thus, a class
that implements Hockey needs to implement all six methods. Similarly, a class that
implements Football needs to define the three methods from Football and the two
methods from Sports.
6. How do you define an interface? Why do the members of interface are static
and final? [M/J2016] [7m]
Interfaces form a contract between the class and the outside world, and this contract is
enforced at build time by the compiler. If your class claims to implement an interface, all
methods defined by that interface must appear in its source code before the class will
successfully compile.
All fields declared within an interface are implicity public, static, and final. Why?

Any implementations can change value of fields if they are not defined as final.
Then they would become a part of the implementation.An interface is a pure
specification without any implementation.

If they are static, then they belong to the interface, and not the object, nor the
run-time type of the object.

An interface provide a way for the client to interact with the object. If variables
were not public, the clients would not have access to them.

In general, a field declaration may include the following modifiers: public, protected,
private, final, static, transient, volatile. But only public, final, and static are permitted for
interface's variable.
Every field declaration in the body of an interface is implicitly public, static, and final. It is
permitted to redundantly specify any or all of these modifiers for such fields. Every field
in the body of an interface must have an initialization expression, which need not be a
constant expression. The variable initializer is evaluated and the assignment performed
exactly once, when the interface is initialized.
36

7. Write a java program to implement nested packages.


file:=Test1.java
package testPack;//this is the outer package
public class Test1
{
public Test1()
{
System.out.println("I am the first class constructor in the parent package");
}
}
//the below file I saved under the above package directory and compiled
file:=Test2.java
package testPack1;//this is the inner package
public class Test2
{
public Test2()
{
System.out.println("I am the first class constructor in the next package");
}
}
//both the packages got created and the below file compiled with the classpath
specified.
file:=NestPack.java
import testPack.*;
import testPack.testPack1.*;
public class NestPack
{
public static void main(String args[])
{
testPack.Test1 t1=new testPack.Test1();
testPack1.Test2 t2=new testPack1.Test2();
}
}

8. Distinguish between arrays and strings .[M/J2016] [3m]


In java, a string array is a collection of string class objects while a char array is a
collection of char (primitive data type) values. ... In C language there is no much
difference among characters and string, except there comes an additional null
character(\0) at the end.

37

9. Explain the method available in the String Bufferf class.[M/J2016] [5m]


Introduction
The java.lang.StringBuffer class is a thread-safe, mutable sequence of characters.
Following are the important points about StringBuffer:

A string buffer is like a String, but can be modified.

It contains some particular sequence of characters, but the length and content of
the sequence can be changed through certain method calls.

They are safe for use by multiple threads.

Every string buffer has a capacity.

Class declaration
Following is the declaration for java.lang.StringBuffer class:
public final class StringBuffer
extends Object
implements Serializable, CharSequence
Class constructors
S.N
.
1

Constructor & Description

S.N
.
1

Method & Description

StringBuffer()
This constructs a string buffer with no characters in it and an initial capacity of
16 characters.
2
StringBuffer(CharSequence seq)
This constructs a string buffer that contains the same characters as the
specified CharSequence.
3
StringBuffer(int capacity)
This constructs a string buffer with no characters in it and the specified initial
capacity.
4
StringBuffer(String str)
This constructs a string buffer initialized to the contents of the specified string.
Class methods

StringBuffer append(boolean b)
This method appends the string representation of the boolean argument to the
38

5
6

10

11
12
13
14

15
16
17

sequence
StringBuffer append(char c)
This method appends the string representation of the char argument to this
sequence.
StringBuffer append(char[] str)
This method appends the string representation of the char array argument to
this sequence.
StringBuffer append(char[] str, int offset, int len)
This method appends the string representation of a subarray of the char array
argument to this sequence.
StringBuffer append(CharSequence s)
This method appends the specified CharSequence to this sequence.
StringBuffer append(CharSequence s, int start, int end)
This method appends a subsequence of the specified CharSequence to this
sequence.
StringBuffer append(double d)
This method appends the string representation of the double argument to this
sequence.
StringBuffer append(float f)
This method appends the string representation of the float argument to this
sequence.
StringBuffer append(int i)
This method appends the string representation of the int argument to this
sequence.
StringBuffer append(long lng)
This method appends the string representation of the long argument to this
sequence.
StringBuffer append(Object obj)
This method appends the string representation of the Object argument.
StringBuffer append(String str)
This method appends the specified string to this character sequence.
StringBuffer append(StringBuffer sb)
This method appends the specified StringBuffer to this sequence.
StringBuffer appendCodePoint(int codePoint)
This method appends the string representation of the codePoint argument to
this sequence.
int capacity()
This method returns the current capacity.
char charAt(int index)
This method returns the char value in this sequence at the specified index.
int codePointAt(int index)
This method returns the character (Unicode code point) at the specified index
39

18

19

20
21
22

23

24

25

26

27

28

29

30
31

32

int codePointBefore(int index)


This method returns the character (Unicode code point) before the specified
index
int codePointCount(int beginIndex, int endIndex)
This method returns the number of Unicode code points in the specified text
range of this sequence
StringBuffer delete(int start, int end)
This method removes the characters in a substring of this sequence.
StringBuffer deleteCharAt(int index)
This method removes the char at the specified position in this sequence
void ensureCapacity(int minimumCapacity)
This method ensures that the capacity is at least equal to the specified
minimum.
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
This method characters are copied from this sequence into the destination
character array dst.
int indexOf(String str)
This method returns the index within this string of the first occurrence of the
specified substring.
int indexOf(String str, int fromIndex)
This method returns the index within this string of the first occurrence of the
specified substring, starting at the specified index.
StringBuffer insert(int offset, boolean b)
This method inserts the string representation of the boolean argument into this
sequence.
StringBuffer insert(int offset, char c)
This method inserts the string representation of the char argument into this
sequence.
StringBuffer insert(int offset, char[] str)
This method inserts the string representation of the char array argument into
this sequence.
StringBuffer insert(int index, char[] str, int offset, int len)
This method inserts the string representation of a subarray of the str array
argument into this sequence.
StringBuffer insert(int dstOffset, CharSequence s)
This method inserts the specified CharSequence into this sequence.
StringBuffer insert(int dstOffset, CharSequence s, int start, int end)
This method inserts a subsequence of the specified CharSequence into this
sequence.
StringBuffer insert(int offset, double d)
This method inserts the string representation of the double argument into this
sequence.
40

33

34

35

36

37
38

39

40
41

42

43

44
45
46

47

48

StringBuffer insert(int offset, float f)


This method inserts the string representation of the float argument into this
sequence.
StringBuffer insert(int offset, int i
This method inserts the string representation of the second int argument into
this sequence.
StringBuffer insert(int offset, long l)
This method inserts the string representation of the long argument into this
sequence.
StringBuffer insert(int offset, Object obj)
This method inserts the string representation of the Object argument into this
character sequence.
StringBuffer insert(int offset, String str)
This method inserts the string into this character sequence.
int lastIndexOf(String str)
This method returns the index within this string of the rightmost occurrence of
the specified substring.
int lastIndexOf(String str, int fromIndex)
This method returns the index within this string of the last occurrence of the
specified substring.
int length()
This method returns the length (character count).
int offsetByCodePoints(int index, int codePointOffset)
This method returns the index within this sequence that is offset from the given
index by codePointOffset code points.
StringBuffer replace(int start, int end, String str)
This method replaces the characters in a substring of this sequence with
characters in the specified String.
StringBuffer reverse()
This method causes this character sequence to be replaced by the reverse of
the sequence.
void setCharAt(int index, char ch)
The character at the specified index is set to ch.
void setLength(int newLength)
This method sets the length of the character sequence.
CharSequence subSequence(int start, int end)
This method returns a new character sequence that is a subsequence of this
sequence.
String substring(int start)
This method returns a new String that contains a subsequence of characters
currently contained in this character sequence
String substring(int start, int end)
41

49
50

This method returns a new String that contains a subsequence of characters


currently contained in this sequence.
String toString()
This method returns a string representing the data in this sequence.
void trimToSize()
This method attempts to reduce storage used for the character sequence.

10. Explain the use of command line arguments with an example. [M/J2016] [8m]
The java command-line argument is an argument i.e. passed at the time of
running the java program.
The arguments passed from the console can be received in the java program
and it can be used as an input.
So, it provides a convenient way to check the behavior of the program for the
different values. You can pass N (1,2,3 and so on) numbers of arguments from the
command prompt.
Simple example of command-line argument in java
In this example, we are receiving only one argument and printing it. To run this java
program, you must pass at least one argument from the command prompt.
class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}
Output:
compile by > javac CommandLineExample.java
run by > java CommandLineExample sonoo
Your first argument is: sono

42

Potrebbero piacerti anche