[go: up one dir, main page]

0% found this document useful (0 votes)
19 views17 pages

Java_BSc(H)_Unit-3

Uploaded by

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

Java_BSc(H)_Unit-3

Uploaded by

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

OBJECT ORIENTED PROGRAMMING USING JAVA UNIT-3

Q) Explain about interface in java?


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.

It cannot be instantiated just like the abstract class.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o 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.
}

RAMAKRISHNAREDDY NANDYALA 9848740143 1


OBJECT ORIENTED PROGRAMMING USING JAVA UNIT-3

The relationship between classes and interfaces


As shown in the figure given below, a class extends another class, an interface extends
another interface, but a class implements an interface.

Java Interface Example


In this example, the Printable interface has only one method, and its implementation is
provided in the A6 class.

interface printable
{
public abstract void print();
}
class A6 implements printable
{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
A6 obj = new A6();

RAMAKRISHNAREDDY NANDYALA 9848740143 2


OBJECT ORIENTED PROGRAMMING USING JAVA UNIT-3

obj.print();
}
}

Output:

Hello

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces, it is
known as multiple inheritance.

Example

interface Printable
{
public abstract void print();
}
interface Showable
{
public abstract void show();
}
class A7 implements Printable,Showable
{
public void print()

RAMAKRISHNAREDDY NANDYALA 9848740143 3


OBJECT ORIENTED PROGRAMMING USING JAVA UNIT-3

{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[])
{
A7 obj = new A7();
obj.print();
obj.show();
}
}

Output:Hello
Welcome

****************************************************************

Q) Explain about packages in java?

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

Benefits:
1. The classes contained in the packages of other program can be easily reused.
2. In packages classes are unique. They are compares with classes in other packages. i.e.
two classes in two different packages can have the same name that may refer by their
fully qualified name, comprising the package name and the class name.
3. Packages provide a way to hide classes. They prevent other programs or packages from
accessing classes that are meant for internal use only.
Java packages are classified into two types.
1. Java API packages (Pre defined packages).
2. User defined packages.

Java API packages (Pre defined packages)


Java API provides a large number of classes grouped into different packages according to
functionality. Most of the time, we use the packages available with the Java API.

RAMAKRISHNAREDDY NANDYALA 9848740143 4


OBJECT ORIENTED PROGRAMMING USING JAVA UNIT-3

Java

lang util io awt net applet


FREQUENTLY USED API PACKAGES

T ABLE 1:J AVA S YSTEM PACKAGES AND T HEIR CLASSES


Package name Contents
Language support classes. These are classes that Java
compiler itself uses and therefore they are automatically
java.lang
imported. They include classes for primitive types, strings,
math functions, threads and exceptions.
Language utility classes such as vectors, has tables, random
java.util
numbers, data etc.
Input/output support classes. They provide facilities for the
java.io
input and output of data.
Set of classes for implementing graphical user interface. They
java.awt
include classes for windows, buttons, list, menus and so on.
Classes for networking. They include classes for
java.net communicating with local computers as well as with internet
servers.
java.applet Classes for creating and implementing applets.

A package is to be included in the user application so that the predefined classes can be used
to achieve this. One can use a keyword called “import”.

Syntax: import package_name.*;

User defined Packages


Simple example of java package

The package keyword is used to create a package in java.

//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");

RAMAKRISHNAREDDY NANDYALA 9848740143 5


OBJECT ORIENTED PROGRAMMING USING JAVA UNIT-3

}
}
How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

1. javac -d directory javafilename

For example

1. 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
How to access package from another package
There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.

1) 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.*


//save by A.java
package pack;

RAMAKRISHNAREDDY NANDYALA 9848740143 6


OBJECT ORIENTED PROGRAMMING USING JAVA UNIT-3

public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

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

2) 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

//save by A.java

package pack;
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();
}
}
Output:Hello

RAMAKRISHNAREDDY NANDYALA 9848740143 7


OBJECT ORIENTED PROGRAMMING USING JAVA UNIT-3

3) 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.

Example of package by import fully qualified name


//save by A.java
package pack;
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();
}
}
Output:Hello

*************************************************************************
**

Q) Explain types of errors in java?


Error is an illegal operation performed by the user which results in the abnormal working
of the program. Programming errors often remain undetected until the program is
compiled or executed. Some of the errors inhibit the program from getting compiled or
executed. Thus errors should be removed before compiling and executing.
The most common errors can be broadly classified as follows:
1. Compile Time Error:
Compile Time Errors are those errors which prevent the code from running because of an
incorrect syntax such as a missing semicolon at the end of a statement or a missing
bracket, class not found, etc. These errors are detected by the java compiler and an error
message is displayed on the screen while compiling. Compile Time Errors are sometimes
also referred to as Syntax errors.

Example : Misspelled variable name or method names

RAMAKRISHNAREDDY NANDYALA 9848740143 8


OBJECT ORIENTED PROGRAMMING USING JAVA UNIT-3

class MisspelledVar {
public static void main(String args[])
{
int a = 40, b = 60;

// Declared variable Sum with Capital S


int Sum = a + b;

// Trying to call variable Sum


// with a small s ie. sum
System.out.println(
"Sum of variables is "
+ sum);
}
}

Compilation Error in java code:


prog.java:14: error: cannot find symbol
+ sum);
^
symbol: variable sum
location: class MisspelledVar
1 error

2. Run Time Error:


Runtime errors occur when a program does not contain any syntax errors but asks the
computer to do something that the computer is unable to reliably do. During compilation,
the compiler has no technique to detect these kinds of errors. It is the JVM (Java Virtual
Machine) that detects it while the program is running.
For example: if the user inputs a data of string format when the computer is expecting an
integer, there will be a runtime error.

3.Logical Error:
A logic error is when your program compiles and executes, but does the wrong thing or
returns an incorrect result or no output when it should be returning an output. These errors
are detected neither by the compiler nor by JVM. The Java system has no idea what your
program is supposed to do, so it provides no additional information to help you find the
error. Logical errors are also called Semantic Errors.

RAMAKRISHNAREDDY NANDYALA 9848740143 9


OBJECT ORIENTED PROGRAMMING USING JAVA UNIT-3

Example: Accidentally using an incorrect operator on the variables to perform an


operation (Using ‘/’ operator to get the modulus instead using ‘%’)
***************************************************************

Q) What is Exception Handling in Java?


Exception:
Exception is a runtime error or any abnormal event in a program is called an
exception
Exception handling is a mechanism it processes the generated exception (it handle runtime
error).
Runtime errors are detected by JVM.
Types of Exception in Java
Exceptions can be categorized into two ways:

1. Built-in Exceptions
o Checked Exception
o Unchecked Exception
2. User-Defined Exceptions

Built-in Exception

Exceptions that are already available in Java libraries are referred to as built-in exception.
These exceptions are able to define the error situation so that we can understand the reason

RAMAKRISHNAREDDY NANDYALA 9848740143 10


OBJECT ORIENTED PROGRAMMING USING JAVA UNIT-3

of getting this error. It can be categorized into two broad categories, i.e., checked
exceptions and unchecked exception.

Checked Exception

Checked exceptions are called compile-time exceptions because these exceptions are
checked at compile-time by the compiler. The compiler ensures whether the programmer
handles the exception or not. The programmer should have to handle the exception;
otherwise, the system has shown a compilation error.

Unchecked Exceptions

The unchecked exceptions are just opposite to the checked exceptions. The compiler will
not check these exceptions at compile time. In simple words, if a program throws an
unchecked exception, and even if we didn't handle or declare it, the program would not give
a compilation error. Usually, it occurs when the user provides bad data during the interaction
with the program.

User-defined Exception
In Java,we already have some built-in exception classes
like ArrayIndexOutOfBoundsException,NullPointerException,and ArithmeticExceptio
n. These exceptions are restricted to trigger on some predefined conditions. In Java, we can
write our own exception class by extends the Exception class. We can throw our own
exception on a particular condition using the throw keyword. For creating a user-defined
exception, we should have basic knowledge of the try-catch block and throw keyword.

Exception Handling
Java provides specific keywords for exception handling purposes.

 try
 catch
 finally
 throw
 throws

try: It is a keyword used to create block of statements which are doubtful of generating
exception.

Syntax:

try

RAMAKRISHNAREDDY NANDYALA 9848740143 11


OBJECT ORIENTED PROGRAMMING USING JAVA UNIT-3

Doubtful code;

Catch: It is a keyword which is used to handle the exceptions. It contains block of


statements (Handling code).

Syntax:

catch(Type of exception Exception object)

Handling code;

Example

import java.lang.*;

class Excep

public static void main(String arg[])

int x=10,y=0,z;

try

z=x/y;

System.out.println(z);

catch(ArithmeticException e)

RAMAKRISHNAREDDY NANDYALA 9848740143 12


OBJECT ORIENTED PROGRAMMING USING JAVA UNIT-3

System.out.println(“Division by zero exception”);

System.out.println(“Progfram over”);

throw: It is a keyword used to create an exception and throw it explicitly. Throw our
own exception using throw keyword. The flow of execution stops immediately after the
throw statements and any subsequent statements are not executed.

Syntax
throw new ExceptionType(“content”);

Example:

import java.lang.*;

class Simple

public static void main(String arg[])

try

throw new ArithmeticException(“This is my own exception”);

System.out.println(“This is try block”);

catch(ArithmeticException e)

System.out.println(e.getmessage());

RAMAKRISHNAREDDY NANDYALA 9848740143 13


OBJECT ORIENTED PROGRAMMING USING JAVA UNIT-3

throws: It is a keyword, it contains list the type of exceptions that a method may throw.
throws keyword is used when we don’t want to handle the exception and try to send the
exception to the JVM.

Syntax:
returntype method name(parameters) throws exception list

---------

--------

Example:

import java.lang.*;

class Simple

static void msg() throws ArithmeticException

int x=10;

int y=0;

int res=x/y;

System.out.println(res);

public static void main(String arg[])

RAMAKRISHNAREDDY NANDYALA 9848740143 14


OBJECT ORIENTED PROGRAMMING USING JAVA UNIT-3

try

Msg();

catch(ArithmeticException e)

System.out.println(“Division by zero error”);

finally: It is a keyword used to create a block of code that will be executed after a
try/catch block whether exception is handle or not.

If an exception occurs then the catch block executes after that finally block will be
executed.

If no exception, then finally block executed.

In case there is an exception, but there is no catch block, then the code execution skips the
rest of code and executes the finally block.

Finally block follows a try block or a catch block.

Syntax:
1. try

Doubtful code;

finally

RAMAKRISHNAREDDY NANDYALA 9848740143 15


OBJECT ORIENTED PROGRAMMING USING JAVA UNIT-3

Executable code;

2. try

Doubtful code;

catch(ExceptionType object)

Handling code;

finally

Executable code;

Example:
import java.lang.*;

class Excep

public static void main(String arg[])

try

RAMAKRISHNAREDDY NANDYALA 9848740143 16


OBJECT ORIENTED PROGRAMMING USING JAVA UNIT-3

int x=10,y=0,z;

z=x/y;

System.out.println(z);

catch(ArithmeticException e)

System.out.println(“Division by zero exception”);

Finally

System.out.println(“Hello this is finally block”);

RAMAKRISHNAREDDY NANDYALA 9848740143 17

You might also like