Java 2
Java 2
An interface declares a set of methods and their signatures. The methods that are declared in an
interface should not have implementation codes.
A Class that makes use of an interface should provide the codes for the methods declared in that
interface.
Structure of an Interface
Interface name
{
type variable-name1=value1;
-
-
type variable n= value n;
return type method name1(args list 1);
-
-
return type method name n(args list n);
}
Implementation of Interface
A class shall make use of an interface by implementing the same. A class that implements an
interface will look as follows
A class can implement more than one interface. In such case , the names of interfaces should be
separated by commas
A class shall extend another class and at the same time, it shall also implement one or more
interfaces.
Examples:
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
Example 2
interface MyInterface
{
public void method1();
public void method2();
}
class XYZ implements MyInterface
{
public void method1()
{
System.out.println("implementation of method1");
}
public void method2()
{
System.out.println("implementation of method2");
}
public static void main(String arg[])
{
MyInterface obj = new XYZ();
obj. method1();
}
}
Example 3
interface Moveable
{
int AVG-SPEED = 40;
void move();
}
class Vehicle implements Moveable
{
public void move()
{
System .out. print in ("Average speed is"+AVG-SPEED");
}
public static void main (String[] arg)
{
Vehicle vc = new Vehicle();
vc.move();
}
}
There are given some points that should be remembered by the java programmer.
o Nested interface must be public if it is declared inside the interface but it can have any
access modifier if declared within the class.
o Nested interfaces are declared static implicitly.
Example of interface implementation
Interface Addtion
{
Void add();
}
Class Find implements Addition
{
Public void add()
{
int a=2,b=5,c;
c=a+b;
System.out.println(“Addition is =”+c);
}
Public static void main(String args[])
{
Find f=new Find();
f.add();
}
}
Though classes in java doesn't suppost multiple inheritance, but a class can implement
more than one interface.
Interface Moveable
{
boolean isMoveable();
}
Interface Rollable
{
boolean isRollable();
}
Class Tyre implements Moveable, Rollable
{
Int width;
boolean isMoveable()
{
return true;
}
boolean isRollable()
{
return true;
}
Public static void main(String args[])
{
Tyre tr=new
Tyre();
System.out.println
(tr.isMovable());
System.out.println
(tr.isRollable());
}
}
Inheritance Interface
Example
Import java.io.*;
Interface intface1
int j=10;
int j1();
Interface intface2
double k1();
boolean b1();
{
public int j1()
return 100;
return 12.8;
return true;
System.out.println(s.j);
System.out.println(s.j1());
System.out.println(s.k1());
System.out.println(s.l1());
Packages
– Built-in package
• E.g. lang, awt, javax, swing, net, io, util, sql etc.
– User-defined package
– E.g. MyPack
• Advantage
– Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
Creating a Package
• The package statement should be the first line in the source file.
• There can be only one package statement in each source file, and it applies to all types in
the file.
• Syntax
package package-name;
• E.g.
package myPack;
• E.g.
package mypack;
System.out.println("Welcome to package");
• The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination.
Access Modifiers
• The access modifiers in java specifies accessibility (scope) of a data member, method,
constructor or class.
– private
– default
– protected
– public
Private
• Try to access these private members from outside the class, so there is compile time error.
//A.Java
package pack;
class A{
System.out.println("Hello java");
//Sample.java
package myPack;
import pack.*;
A obj=new A();
System.out.println(obj.data);//Compile Time Error
Default
• We are accessing the A class from outside its package, since A class is not public, so it
cannot be accessed from outside the package.
//A.java
package pack;
class A {
System.out.println("Hello");
//B.java
package mypack;
import pack.*;
class B{
Protected
• Create the two packages muthuPack and myPack.
• The Sample class of muthuPack package is public, so can be accessed from outside the
package.
• But msg() method of this package is declared as protected, so it can be accessed from
outside the class only through inheritance.
• E.g.
package muthuPack;
System.out.println("Hello");
package myPack;
import muthuPack.*;
obj.msg();
}
Public
• E.g.
package myAddPack;
int x, y;
x=10;
y=20;
package demoPack;
import myAddPack.*;
class AddDemo {
obj.sum();
• There are three ways to access the package from outside the package.
– import package.*;
– import package.classname;
1. Using packagename.*
• If you use package.* then all the classes and interfaces of this package will be accessible
but not sub-packages.
• The import keyword is used to make the classes and interface of another package
accessible to the current package.
//A.java
package pack;
public class A {
System.out.println("Hello");
//B.java
package mypack;
import pack.*;
class B {
obj.msg();
2. Using packagename.classname
• If you import package.classname then only declared class of this package will be
accessible.
//A.java
package pack;
public class A{
System.out.println("Hello");
}
//B.java
package mypack;
import pack.A;
class B{
obj.msg();
• 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.
//A.java
package pack;
public class A{
//B.java
package mypack;
class B{
obj.msg();
}
Subpackages
• Package inside the package is called the subpackage. It should be created to categorize the
package further.
– E.g. Sun 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.
• E.g.
//Class_A.java
package myFirst;
System.out.println("Hi...");
}
//Class_B.java
package myFirst.mySecond;
import myFirst.*;
System.out.println("Hello...");
//Class_C.java
package myFirst.mySecond.myThird;
import myFirst.mySecond.*;
System.out.println("Good Morning...");
//DemoPackage.java
package mySubPack;
import myFirst.mySecond.myThird.*;
import myFirst.mySecond.*;
import myFirst.*;
class DemoPackage
objc.morning();
objb.hello();
obja.hi();
}
Exception Handling
What is an exception?
An Exception can be anything which interrupts the normal flow of the program. When an
exception occurs program processing gets terminated and doesn’t continue further. In such cases
we get a system generated error message. The good thing about exceptions is that they can be
handled. We will cover the handling part later in this same tutorial.
Errors indicate serious problems and abnormal conditions that most applications should not try
to handle. Error defines problems that are not expected to be caught under normal circumstances
by our program. For example memory error, hardware error, JVM error etc.
Exceptions are conditions within the code. A developer can handle such conditions and take
necessary corrective actions. Few examples –
• DivideByZero exception
• NullPointerException
• ArithmeticException
• ArrayIndexOutOfBoundsException
Advantages of Exception Handling
• Exception handling allows us to control the normal flow of the program by using
exception handling in program.
• It throws an exception whenever a calling method encounters an error providing that the
calling method takes care of that error.
• It also gives us the scope of organizing and differentiating between different error types
using a separate block of codes. This is done with the help of try-catch blocks.
Why to handle exception?
If an exception is raised, which has not been handled by programmer then program execution can
get terminated and system prints a non user friendly error message.
Types of exceptions
1)Checked exceptions
2)Unchecked exceptions
Below is a brief about each however if you want a detailed tutorial with examples then you can
refer Checked and Unchecked exceptions in Java.
Checked exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler
checks them during compilation to see whether the programmer has handled them or not. If these
exceptions are not handled/declared in the program, it will give compilation error.
Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions as the compiler do not check
whether the programmer has handled them or not but it’s the duty of the programmer to handle
these exceptions and provide a safe exit.
These exceptions need not be included in any method’s throws list because compiler does not
check to see if a method handles or throws these exceptions.
The try block contains a block of program statements within which an exception might occur. A
try block is always followed by a catch block, which handles the exception that occurs in
associated try block. A try block must followed by a Catch block or Finally block or both.
Syntax of try block
try{
//statements that may cause an exception
}
What is Catch Block?
A catch block must be associated with a try block. The corresponding catch block executes if an
exception of a particular type occurs within the try block. For example if an arithmetic
exception occurs in try block then the statements enclosed in catch block for arithmetic
exception executes.
try
{
//statements that may cause an exception
}
catch (exception(type) e(object))
{
//error handling code
}
1. If an exception occurs in try block then the control of execution is passed to the catch
block from try block. The exception is caught up by the corresponding catch block. A
single try block can have multiple catch statements associated with it, but each catch block
can be defined for only one exception class. The program can also contain nested try-
catch-finally blocks.
2. After the execution of all the try blocks, the code inside the finally block executes. It is
not mandatory to include a finally block at all, but if you do, it will run regardless of
whether an exception was thrown and handled by the try and catch blocks.
An example of Try catch in Java
class Example1 {
public static void main(String args[]) {
int num1, num2;
try {
// Try block to handle code that may cause exception
num1 = 0;
num2 = 62 / num1;
System.out.println("Try block message");
} catch (ArithmeticException e) {
// This block is to catch divide-by-zero error
System.out.println("Error: Don't divide a number by zero");
}
System.out.println("I'm out of try-catch block in Java.");
}
}
Output:
catch(Exception e){
//This catch block catches all the exceptions
}
3. If multiple catch blocks are present in a program then the above mentioned catch block should
be placed at the last as per the exception handling best practices.
4. If the try block is not throwing any exception, the catch block will be completely ignored and
the program continues.
5. If the try block throws an exception, the appropriate catch block (if one exists) will catch it
–catch(ArithmeticException e) is a catch block that can catch ArithmeticException
–catch(NullPointerException e) is a catch block that can catch NullPointerException
6. All the statements in the catch block will be executed and then the program continues.
class Example2{
public static void main(String args[]){
try{
int a[]=new int[7];
a[4]=30/0;
System.out.println("First print statement in try block");
}
catch(ArithmeticException e){
System.out.println("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e){
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block...");
}
}
Output:
Warning: ArithmeticException
Out of try-catch block...
Class: Java.lang.ArithmeticException
This is a built-in-class present in java.lang package. This exception occurs when an integer is
divided by zero.
class ExceptionDemo1
{
public static void main(String args[])
{
try{
int num1=30, num2=0;
int output=num1/num2;
System.out.println ("Result = " +output);
}
catch(ArithmeticException e){
System.out.println ("Arithmetic Exception: You can't divide an integer by 0");
}
}
}
Output of above program:
Explanation: In the above example I’ve divided an integer by a zero and due to
which ArithmeticException is thrown.
Class: Java.lang.ArrayIndexOutOfBoundsException
This is a built in class present in java.lang package. This exception occurs when the referenced
element does not exist in the array. For e.g. If array is having only 5 elements and we are trying
to display 7th element then it would throw this exception.
Example:
class ExceptionDemo2
{
public static void main(String args[])
{
try{
int a[]=new int[10];
//Array has only 10 elements
a[11] = 9;
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("ArrayIndexOutOfBounds");
}
}
}
Output:
ArrayIndexOutOfBounds
In the above example the array is initialized to store only 10 elements indexes 0 to 9. Since we
are invoking index 11 that’s why it is throwing this exception.
Class: Java.lang.NumberFormatException
The object of the above built-in class gets created whenever a string is parsed to any numeric
variable.
For E.g. The statement int num=Integer.parseInt ("XYZ") ; would
throw NumberFormatException because String “XYZ” cannot be parsed to int.
Complete Code:
class ExceptionDemo3
{
public static void main(String args[])
{
try{
int num=Integer.parseInt ("XYZ") ;
System.out.println(num);
}catch(NumberFormatException e){
System.out.println("Number format exception occurred");
}
}
}
Output:
Class: Java.lang.StringIndexOutOfBoundsException
• An object of this class gets created whenever an index is invoked of a string, which is not
in the range.
• Each character of a string object is stored in a particular index starting from 0.
• To get a character present in a particular index of a string we can use a method
charAt(int) of java.lang.String where int argument is the index.
E.g.
class ExceptionDemo4
{
public static void main(String args[])
{
try{
String str="easysteps2buildwebsite";
System.out.println(str.length());;
char c = str.charAt(0);
c = str.charAt(40);
System.out.println(c);
}catch(StringIndexOutOfBoundsException e){
System.out.println("StringIndexOutOfBoundsException!!");
}
}
}
Output:
22
StringIndexOutOfBoundsException!!
Exception occurred because the referenced index was not present in the String.
An object of this class gets created whenever a member is invoked with a “null” object.
Example:
package beginnersbook.com;
class Exception2
{
public static void main(String args[])
{
try{
String str=null;
System.out.println (str.length());
}catch(NullPointerException e){
System.out.println("NullPointerException..");
}
}
}
Output:
NullPointerException..
Here, length() is the function, which should be used on an object. However in the above
example String object str is null so it is not an object due to
which NullPointerException occurred.
Syntax:
try
{
.
.
.
}
catch(ExceptionType 1 parameters1)
{
.
.
.
.}
catch(Exception Type2 Parameter 2)
{
.
.
.
}
finally
{
.
.
.}
Example
class ExceptionDemo1
{
public static void main(String args[])
{
try{
int num1=30, num2=0;
int output=num1/num2;
System.out.println ("Result = " +output);
}
catch(ArithmeticException e){
System.out.println ("Arithmetic Exception: You can't divide an integer by 0");
}
finally
{
System.out.println(“Finally Block”);
}
}
Output:
Arithmetic Exception: You can't divide an integer by 0
Finally Block
Throws CLAUSE
Import java.io.*;
Class test
{
public static void main(String args[])
{
try{
System.out.print(“Enter a String”);
String s=valueReader1();
System.out.println("Result = " +s);
}
catch(IOException e){
System.out.println ("IO error has occurred");
}
{
Static string valueReader1() throws IOException
{
InputStreamReader reader=new InputStreamReader(System.in);
BufferedReader input=new BufferedReader(reader);
String text=input.readLine();
return text;}}