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

1

CORE JAVA

1. Introduction:
Java is an object-oriented programming developed by Sun Microsystems, in 1991.( January 27,
2010: Oracle acquires Sun Microsystems.) Java has become the widely used programming language
for the Internet. Although wile designing the language, the primary object was to develop a
programming language, which is platform-independent.
Java was developed by Pertick Naughton,Chris,and other team members in around 1995.
Intially Java, was known as "OAK". There was a myth that the java programmers are very found
of Coffee so, they named the language in name of the coffee. But latter on due to some trade mark
problems it was later renamed to java. In the name of the Island, where the coffee trees are found.

Java can be used to develop many types of applications:

 Standalone Applications
 Applets
 Web applications
 Distributed Applications

Standalone Applications

 A standalone Applications is a program that runs on your computer. it is more or less like a
C or C++ program.

Initially Java was developed to write the code or programs for the electronic devices such as
Washing Machines, microwave ovens etc..., are in the java we can write code without worrying
about the platform and the operating systems.
With the origin of the Internet, the Java becomes more popular.

Why Java is Important to Internet?


In the case of Internet, there are millions and millions of computers connected to the computers
system. And these computers may vary in platforms.

BMB Projects ‘N’ Training


2

2. First Java Program:


Program-1
class Sample
{
public static void main(String [ ]args)
{
System.out.print ("Hello World");
System.out.println("Hello World");
}
}

(a) class Sample


class is the keyword to define a class .The general form of the class definition is ,
class Classname
{
body of the class
}

It is the general convention to write the first letter of the class name in capital. In c++, we can write
the programs which does not contain the classes, but in case of the java the program should contain
at least one class definition.

Note: that the Java is also case-sensitive.

(b) public static void main(String args[ ])


public:
This keyword is used to specify that the specific item will be considered as global, so it can
be used anywhere in the class definition.
static:
The static keyword is used to specify that only one copy of main() should be maintained as
only one main() method is allowed in the class definition.

BMB Projects ‘N’ Training


3

void:
It is used to specify that the function will not return any value.
main():
Each of the Java application program must contain atleast one method, that is, main( ), the
execution of the program starts from the main() method.
String :
String is the predefined class, used for handling the group of characters that is string. This
class is present in the package known as java.lang.

Packages are like the header files, as the header files are the collection of the
functions, the packages are the collection of the classes.
The package java.lang is the default package of java, so it is not required that we
should import that package, all the classes which are defined in this packages can be used directly.
args[ ]
The args[ ] is an array of String class objects used for storing the command line arguments.

Source File Structure

All java source files must end with the extension “ .java “ . A source file may contain at the
most one top-level public class. If a public class is present, the un-extended file name
should be same as the class name i.e. if the class name is Hello then the source file name
should be Hello.java. if a source file does not contain any public class then name of the
source file can be anything.
A source file may contain an unlimited number of non-public class definitions.
There are four top-level elements that may appear in a file. None of these elements is must.
If they are present, then must appear in the following order:
(i) Package declaration
(ii) Import statements
(iii) Class and/or interface definitions.

BMB Projects ‘N’ Training


4

3. Running a java application:

When a program is compiled, it is directly translated into machine code that is specific to a platform
/processor. But running java program is a two-step process. In java translation from source code to
the executable code is achieved using two translators.

1. Java compiler
2. Java interpreter
1. Java compiler: A java program is first complied by the java compiler to generate bytecode.
Bytecode resemble machine code but it not specific to any platform i.e. it can’t be executed on a
computer without further translation.
2. Java Interpreter: java Interpreter executes the bytecode after interpreting and converting into
machine code.

Java programs run at a slower speed as compared to C/C++programs as bytecode is interpreted


during each run while in case of C/C++, source code is compiled only once into the executable
code, which then runs directly on the hardware. In order to write and run a java program we need an
editor, Java Compiler and a java runtime environment.

The editor can be any text editor like notepad, WordPad, edit etc.
The easiest way to get a java compiler and runtime environment is to download and install Sun`s
java Development kit (JDK).
Example: the note following java program just displays the massage “Hello Word” on the
monitor/consol.
Note: the JDK must be installed on the machine before you can compile and run the java program.
If you install the JDK in folder c:\jdk\bin then this folder must be in the “PATH” so that you cam
compile and run tour java program from any folder. Give the following command in the command
window from which you want to compile and run the java program:

SET PATH=%PATH%;C:\JDK\BIN;

BMB Projects ‘N’ Training


5

Program-2

class Sum2
{
public static void main(String args[ ])
{
int a,b,c;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
/*calculate the sum */
c=a+b;
System.out.println("Sum = "+c);
}
}

4.Comments

A program can be documented by inserting comments wherever required. The comment are simply
ignored by the compiler.

Java provides three types of comments for documentation:

 Single-line comment
 Multi-line comment
 Documentation comment

Single-line comment:
A single-line comment spans only one line. It can be given on any line followed by the character
“//”. The syntax is similar to C++.
Multi-line comment:

BMB Projects ‘N’ Training


6

The syntax of a multi-line comment is same as in C/C++. A multi-line comment is enclosed


between “/*” and “*/”.

5. Class And Objects:


The class binds together data and methods which work on data. Class defines a general category
and an object is an instance or an occurrence of a class. The class consists of the data items as well
as the code or the functions which manipulate these data items

The general form of class is:


class ClassName
{
datatype1 datamembername1;
datatype2 datamembername2;
: : : : : : : :
: : : : : : : :
Datatype datamembernamen;
returntype1 functioname1(argument list1)
{
body of the functionname1
}
: : : :
: : : :
}

Program-3

class Sample
{
int a,b;
void setAll(int i,int j)
{

BMB Projects ‘N’ Training


7

a=i;
b=j;
}
void showAll( )
{
System.out.println("a= " + a + " b="+b);
}
}
class SampleDemo
{
public static void main(String args[ ])
{
Sample ob=new Sample( );
ob.setAll(5,6);
ob.showAll( );
Sample ob1=new Sample( );
Ob1.showAll( );
}
}

(i) class Sample


The class is the keyword to define a class. The general form is:-
class Classname
{
: : : :
: : : :
}

It is the general convention to write the first letter of the class name in capital.

(ii) int a,b;


This statement will declare the two variable or data items with name a and b.

BMB Projects ‘N’ Training


8

(iii) setAll( ) and showAll( ):-


These are functions of the class Sample and the setAll( ) function is used to initialize the data items
a and b and the showAll( ) function is used to display the data item a and b.

(iv) class SampleDemo


Now, in this program we have two class definition, the first class definition will define the class
Sample and the second class definition will contain the main( ) method definition.

Now, we will save the program with the same name that of the class one which contain the main()
method definition.

So, in our case the program file will be saved with the name SampleDemo.java.

(v) Sample ob=new Sample( ):


This statement will create the object of the class Sample and with the name ob.

The general form is:


Classname objectname= new Classname( );

(vi) ob.setAll(5,6);
ob.showAll( );
In order to access any of the members of the class we have to first create the object of that class and
we have to make use of the (.) dot operator.

The general form is:


Object_name.member_name

6. Input from keyboard:

BMB Projects ‘N’ Training


9

With JDK1.5, Scanner class was added to read input from keyboard as well as file. for example the
following code allows a user to read a number from keybord:
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();

Program-4
import java.util.*;
class input
{
public static void main(String ab[])
{
Scanner sc=new Scanner(System.in);
int a,b,c;
System.out.println("a=");
a=sc.nextInt();
System.out.println("b=");
b=sc.nextInt();
c=a+b;
System.out.println("add="+c);
}
}
Java Read through DataInputStream:
import java.io.*;
class ReadFromDataInputStream{
public static void main(String[] args) throws Exception{
DataInputStream in = new DataInputStream(System.in);
System.out.println("Enter Name: ");
String name=in.readLine();
System.out.println("Name is: "+name);
}
}
Java read input through Scanner:

BMB Projects ‘N’ Training


10

import java.util.*;
class ScannerExample
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
System.out.print("Enter integer: ");
int i=input.nextInt();
System.out.print("Enter double: ");
double d=input.nextDouble();
System.out.print("Enter float: ");
float f=input.nextFloat();
System.out.print("Enter string: ");
String s=input.next();
System.out.println(i);
System.out.println(d);
System.out.println(f);
System.out.println(s);
}
}

Java read input through BufferedReader

import java.io.*;
class ReadFromBufferedReader {
public static void main(String[] args)throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Name: ");
String input = reader.readLine();
System.out.println("Name is: "+input);
}
}

BMB Projects ‘N’ Training


11

7. Allocating memory using operator new:

The memory for java objects is always allocated dynamically with the help of new operator.

Example:

ABC abc=new ABC();

8. Method Overloading:
We can have more than one method with the same name as long as they differ either in number of
parameters or type of parameters. This is called method overloading. The difference in the method
call is made on the basis of,

* Number of arguments
* Type of arguments
* Sequence of arguments

PROGRAM-5

class Overload
{
void area(int side)
{
int ar;

ar=side*side;

System.out.println("Area of Square :"+ar);


}
void area(double radius)
{
double ar;

ar=3.14*radius*radius;

System.out.println("Area of Circle :"+ar);


}

void area(int length,int width)


{
int ar;

ar=length*width;

System.out.println("Area of Rectangle:"+ar);

BMB Projects ‘N’ Training


12

}
}
class OverDemo
{
public static void main(String args[ ])
{
Overload ob=new Overload( );

ob.area(5);

ob.area(8,9);

ob.area(6.7);

}
}

(i) ob.area(5);
In this function call we have passed only the single argument of type int so the
function calculating the area of square will get called.

(ii) ob.area(8,9);
In this function call ,we have passed the two argument of type integer , so the
function calculating the area of rectangle will get called.

(iii) ob.area(6.7);
In this function call, we have passed a single argument of type double, so the
function calculating the area of circle will get called.

PROGRAM-6

Q Define the class Interchange which will contain the overloaded definitions of the swap function ,
which will be used for swapping integers, double and character type values .

class Interchange
{
void swap(int a,int b)
{
int c;
c=a;
a=b;
b=c;
System.out.println(“a= “ + a + “ b = “ + b);
}
void swap(char a,char b)
{

BMB Projects ‘N’ Training


13

char c;
c=a;
a=b;
b=c;
System.out.println(“a= “ + a + “ b = “ + b);
}
void swap(double a,double b)
{
double c;
c=a;
a=b;
b=c;
System.out.println(“a= “ + a + “ b = “ + b);
}
}
class InterDemo
{
public static void main(String args[ ])
{
Interchange ob=new Interchange();
ob.swap(5,6);
ob.swap(‘d’,’e’);
ob.swap(5.23,6.98);
}
}

9.Constructor:
It very common requirement to initialize an object immediately after creation. We can
define non-static methods for this purpose but they have to be invoked explicitly. Java has a
solution for this requirement. Java allows objects to initialize themselves when they are created
using constructors.
The constructor is the special member function which have the same name that of the class.
The constructor has not return type not even void. The constructor get called when the object is
created. The constructor is used to allocate the memory resources occupied by the object.

The general form is ,

classname( )
{
body of the constructor
}

BMB Projects ‘N’ Training


14

PROGRAM-7
class Sample
{
Sample( )
{
System.out.println("Constructor called");
}
}
class ConsDemo
{
public static void main(String args[ ])
{
Sample ob=new Sample( );
}
}

When the statement ,


Sample ob=new Sample( );
will get executed the constructor will get called.

output :

Constructor called.

Parameterized Constructor:

The constructor which take argument from the user are said to be parameterized constructor.

The general form is ,

Classname(argument list)
{
body of the constructr
}

PROGRAM-8
class Sample
{
int i;

Sample( ) //default constructor


{
i=0;
}

Sample( int a )//parameterized constructor

BMB Projects ‘N’ Training


15

{
i=a;
}

void show( )
{
System.out.println("i="+i);
}
}
class ConsDemo2
{
public static void main(String args[ ])
{
Sample ob1=new Sample( );

ob1.show( );

Sample ob2=new Sample(5);

ob2.show( );

}
}

(i) Sample ob1=new Sample( );

In this case, we have not passed any argument in the constructor, so the default constructor
will get called.

So, the data member is of object ob1 will get initialized with 0.

(ii) Sample ob2=new Sample(5);

In this case, we have passed a single argument of type int so the parameterized constructor
taking one integer argument will get called.

BMB Projects ‘N’ Training


16

10.Inheritance:

The term "Inheritance" refers to creating a new class on the basis of the existing class. The new
class is known as the derived class and the existing class is known as the base class.
The derived class has more or less all features of the base class and some new features of its own.
The general form is,
class DerivedClassName extends BaseClassName
{
body of the Derived Class
}

Extending a class:

The extend keyword is used for creating the derived class. To inherit a class, you simply
incorporate the definition of one class into another by using the extend keyword.
Java support only Single-Inheritance (Simple Inheritance) in the case of classes to avoid ambiguity
and complexity although it supports Multiple- Inheritance in the case of interfaces.
The general form for deriving a sub-class from an existing class in us follow.
Class <sub-class> extend <base-class>
{
<class-definition>
}

Member Hiding:

If a sub-class member has the same name (and same signature in case of methods) as that of a
super-class member then it hides the super-class member. Although both the members might be
available in the sub-class but using member name we can only access sub-class member us it hides
the member of some name in the super-class.

Private Members:

In the case of inheritance, the private members have the following features,
(i) These members are not directly accessible by the object of a class.

BMB Projects ‘N’ Training


17

e.g.
ob.b=10; is Invalid
(ii) These members will not get inherited. That is, they cannot be used in the derived class or
by the object of the derived class.
showB()
System.out.println("a="+a);
it will be invalid

Public Members:
In the case of inheritance, the public members have the following features,
(i) These members are directly accessible by the object of a class.
e.g.
ob.setA(5) ; is valid
(ii) These members will get inherited.
That is, they can be used in the derived class or by the object of the derived class.
B ob=new B();
ob.showA();

Type of Inheritance:
(a) Single Inheritance
(b) Multilevel Inheritance
(c) Hierarchical Inheritance
(d) Hybrid Inheritance

BMB Projects ‘N’ Training


18

BMB Projects ‘N’ Training


19

(a) Single Inheritance:

In the case of Single Inheritance, we derive the single derived class, on the basis of the single base
class.
PROGRAM-9
class A
{
private int a;
public void setA(int i)
{
a=i;
}
public void showA( )
{
System.out.println("a="+a);
}
}
class B extends A
{
private int b;
public void setB(int j)
{
b=j;
}
public void showB( )
{

BMB Projects ‘N’ Training


20

System.out.println("b="+b);
}
}
class SingleDemo
{
public static void main(String args[ ])
{
B ob=new B( );
ob.setA(5);
ob.setB(10);
ob.showA();
ob.showB();
}
}
(b) Multilevel Inheritance
In the case of the multilevel inheritance, we first create a derived class on the basis of the single
base class. Then on the basis of this derived class, we create another derived class and so on...

BMB Projects ‘N’ Training


21

PROGRAM-10
class A
{
private int a;
public void setA(int i)
{
a=i;
}
public void showA( )
{
System.out.println("a="+a);
}
}
class B extends A
{
private int b;
public void setB(int j)
{
b=j;
}
public void showB( )
{
System.out.println("b="+b);
}
}
class C extends B
{
private int c;
public void setC(int k)
{
c=k;
}

BMB Projects ‘N’ Training


22

public void showC( )


{
System.out.println("c="+c);
}
}
class MutiLevel
{
public static void main(String args[ ])
{
C ob=new C( );
ob.setA(5);
ob.setB(10);
ob.setC(15);
ob.showA();
ob.showB();
ob.showC();
}
}

(c) Hierarchical Inheritance:


In this type of inheritance, we create multiple derived classes on the basis of the single base class.

PROGRAM-11
class A

BMB Projects ‘N’ Training


23

{
private int a;
public void setA(int i)
{
a=i;
}
public void showA( )
{
System.out.println("a="+a);
}
}
class B extends A
{
private int b;
public void setB(int j)
{
b=j;
}
public void showB( )
{
System.out.println("b="+b);
}
}
class C extends A
{
private int c;
public void setC(int k)
{
c=k;
}
public void showC( )
{

BMB Projects ‘N’ Training


24

System.out.println("c="+c);
}
}
class HLevel
{
public static void main(String args[ ])
{
B ob1=new B( );
ob1.setA(5);
ob1.setB(10);
ob1.showA();
ob1.showB();
C ob2=new C( );
ob2.setA(19);
ob2.setC(15);
ob2.showA();
ob2.showC();
}
}
(d) Hybrid Inheritance:
It is a mixture of two or more types of inheritance.

BMB Projects ‘N’ Training


25

11.Operators:

Expression
The Expression is the valid combination of operators and operands. Operators are
one which perform the operation and the operands are one on which the operation is performed.
e..g.
3*4+5 is an expression .
Operators are * and + , and Operands are 3,4 and 5.

Operators in Java:

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operators
 Conditional Operator
 Increment and Decrement Operator
 Bitwise Operators
 Special Operators

Priority Of Operators
{}
()
!
*,/,%
+,-
>,<,>=,<=
==,!=
&&
||
=

(i) Arithmetic Operators:


These Operators are used to perform the calculation
Java has five arithmetic operators:

Operator Description

+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus

The behaviour of the +,-,*,/ operator is same e as c,c++. The modulus operator can be applied to

BMB Projects ‘N’ Training


26

integer as well as floating-point type while in case of c/c++ it can be applied to integer type only.
Important Rule Regarding calculating the Modulus:

To calculate the modulus, ignore the sign and calculate the remainder and the sign of the
resultant value will depends on the sign of the left operand in the expression.

Example:
int i=5%2;
int j=-5%2;
int k=5%-2;
int m=-5%-2;

Answer:
i=1
j=-1
k=1
m=-1

(ii) Relational Operators:


The Relational operators are used for comparing the two values and the result of the
comparison is a Boolean value i.e. true or false.

Java supports the following ordinal comparisons / relational operators.


Operator Description
> Greater Than
< Less Than
>= Greater than or equal to
<= Less than or equal to
== Equal to
!= Not equal to

These operators are used to compare ordinal data types. Data types where values have numeric
order.

(iii) Logical Operators:

There are three types of Logical Operators:

(a) Logical AND(&&)


(b) Logical OR(||)
(c) Logical NOT(!)

(a) Logical AND (&&)

The Logical AND (&&) operators is used to combine two conditions and the result
of the operation is true if and only if both of the conditions are true.

BMB Projects ‘N’ Training


27

The truth table of the Logical AND


Condition1 Condition2 Condition1&&Condition2
false false false
false true false
true false false
true true true

It is also known as the Short Circuit Logical AND Operator because if the first condition
hold false it will not check the second condition.

(b) Logical OR(||)

The Logical OR (||) operators are used to combine two conditions and the result of
the operation is true if any of the one or both conditions are true.

The truth table of the Logical OR

Condition1 Condition2 Condition1||Condition2


false false false
false true true
true false true
true true true

It is also known as the Short Circuit Logical OR Operator because if the first condition hold
true it will not check the second condition.

(c) Logical NOT(!)

This operator is used to reverse the condition and if the condition is true then the condition
will become false and if the condition is false then the condition will become true.
The truth table of the Logical NOT(!)
Condition !Condition
false true
true false

(iv) Assignment Operator:


The = operators is known as the Assignment Operators and it is used to assign the value into
the variable.
Syntax: <Variable> = <expression>
Example:
a=2
It will assign the value 2 into the variable a

a==2
It will compare whether the value stored in the variable a is equal to 2 or not.

BMB Projects ‘N’ Training


28

(v) Increment and Decrement Operators:

++ Operator is known as Increment Operator and it is used to increase the value of variable by 1.
There are two types of Increment Operators:

(i) Pre-Increment Operator

(ii) Post-Increment Operator

(i) Pre-Increment Operator


In this case, first the increment operation is performed and then the other operation
will take place.

Consider the following example:

i=6;

j=++i;

So, the above statement is equivalent to ,


i=i+1==> i=6+1=7

j=i; ==> j=7

(ii) Post-Increment Operator


In this case, first the other operation is performed, and then the increment will take
place.

Consider the following example:

i=6

j=i++;
The above mentioned statement is equivalent to

j=i; ==> j=6

i=i+1 ==> i=6+1==> 7

Consider the following code,

int a=4;

int b,c;

b=2*(a++);

c=2*(++a);

BMB Projects ‘N’ Training


29

Find out the final value of a, b, and c?

a=6 , b=8 , c=12

y=2;
y=++y*y++*++y;

Decrement Operators:
(i) Pre- Decrement Operators:
(ii) Post- Decrement Operators:

(vi) Bitwise Operators:

Java's bitwise operators operate on individual bits of integer (int and long) values. If an operand is shorter
than an int, it is promoted to int before doing the operations.
The bitwise operators operates on the individuals bits of the numbers. To perform the
operators, we have to convert them into their binary equivalents.
List of the Bitwise Operators:

(i) One's Complement


(ii) Bitwise AND(&)
(iii) Bitwise OR(|)
(iv) Bitwise XOR(^)
(v) Bitwise Arithmetic Right Shift (>>)
(vi) Bitwise Unsigned Right Shift (>>>)
(vii) Bitwise Left Shift

The bitwise operators:

Operator Name Example Result Description


a & b And 3&5 1 1 if both bits are 1.
a | b Or 3|5 7 1 if either bit is 1.
a ^ b Xor 3^5 6 1 if both bits are different.
~a Not ~3 -4 Inverts the bits.

n << p
left Shifts the bits of n left p positions. Zero bits are shifted
3 <<< 2 12
shift into the low-order positions.
Shifts the bits of n right p positions. If n is a 2's
n >> p
right
5 >> 2 1 complement signed number, the sign bit is shifted into the
shift
high-order positions.

n >>> p
right Shifts the bits of n right p positions. Zeros are shifted into
-4 >>> 28 15
shift the high-order positions.

BMB Projects ‘N’ Training


30

12.Array:
Array in java is ordered collection of similar type of variables. Java allows creating arrays in any
dimension. An array in java is a bit different from C/C++. You can not specify the size of the array
at the time of declaration. The memory allocation is always dynamic.
An array is a group of liked type variables that are referenced by same name. A specific
element of that Array is accessed by its index.
Type:
One-Dimensional Array:
Its a list of liked type variables. To use an array, you first must create it with a name
and proper size.
Declaration:
type var_name[size];
Here type declares the base type of the array. var_name defines the name of the array and size is the
number of element.
Example:
int month_days[ ];
the following declaration shows an array with null value. To link month_days
with an actual and physical array, you must allocate one with new. new is a special
keyword used to allocate memory.
array_var = new type[size];
month_days = new int[12];
After this statement executes, month_days, will refer to an array of 12 integer. further all element of
the array will br initializes to zero.

PROGRAM-
class bmbArray
{
public static void main(String args[])
{
int month_days[ ];
month_days = new int[12];

BMB Projects ‘N’ Training


31

month_days[0]=31;
month_days[1]=28;
month_days[2]=31;
month_days[3]=30;
month_days[4]=31;
month_days[5]=30;
month_days[6]=31;
month_days[7]=31;
month_days[8]=30;
month_days[9]=31;
month_days[10]=30;
month_days[11]=31;
System.out.println("April has" +month_days[3]+ "days");

}
}

it is also possible to combine the declaration of the array variable with the array allocation. like,
int month_days[ ] = new int[12];
you can also initialize the array elements like that,

PROGRAM-
class bmbarray
{
public static void main(String aregs[ ])
{
int month_days[ ] = {31,28,31,30,31,30,31,31,30,31,30,31};

System.out.println("April has" + month_days[3] + "days");


}
}

BMB Projects ‘N’ Training


32

Multi- Dimensional Array:


Declaration:
Type vari_name[][];
The type specifies the base type of array element as in the case of one-dimensional array. For
example:
The following array used to store integers element:
in tab[][]; or int[][]ab;
or
int twod[ ] [ ] = new int [4] [5];
This allocates a 4 by 5 array and assign it to twod. Internally this matrix is implemented as "Array
of Array" of int type.
Memory Allocation:
Var=new type[rows][columns];
The variable var is the name of two-dimensional array. The type refers to the type of the elements
that can be stored in array. The first index indicates the number of rows and the second index
indicates the number of columns in the two-dimensional array to be allocated dynamically.

PROGRAM-
Class TwoDArray
{
public static void main(String args[ ])
{
int twod [ ] [ ] = new int [4] [5];
int i,j,k=0;
for(i=0;i<=4;i++)
for(j=0;j<=5;j++)
{
twod[i][j]=k;
k++;
}

BMB Projects ‘N’ Training


33

for(i=0;i<=4;i++)
{
for(j=0;j<=5;j++)
System.out.println(twod[i][j] + " ");
}
}
}

PROGRAM-
Matrices addition:

import java.util.*;
class autoarray
{
public static void main(String a[])
{
int mat1[][],mat2[][],mat3[][];
int rows,cols;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the no of rows:");
rows=sc.nextInt();
System.out.println("Enter the no of cols:");
cols=sc.nextInt();
mat1=new int[rows][cols];
mat2=new int[rows][cols];
mat3=new int[rows][cols];
System.out.println("Enter the elements of first matrix:");
for(int i=0;i<rows;i++)
{
for(int j=0; j<cols;j++)
{
mat1[i][j]=sc.nextInt();

BMB Projects ‘N’ Training


34

}
}
System.out.println("Enter the elements of second matrix:");
for(int i=0;i<rows;i++)
{
for(int j=0; j<cols;j++)
{
mat2[i][j]=sc.nextInt();
}
}
for(int i=0;i<rows;i++)
{
for(int j=0; j<cols;j++)
{
mat3[i][j]=mat1[i][j]+mat2[i][j];
}
}
System.out.println("Result is:");
for(int i=0;i<rows;i++)
{
for(int j=0; j<cols;j++)
{
System.out.print(mat3[i][j]+" ");
}
System.out.println();
}
}
}

BMB Projects ‘N’ Training


35

13.Exception Handling:
An exception/error is an abnormal condition that breaks/disrupts the normal program flow. The
abnormal condition occurs at run-time i.e. during code execution.

For example, a C program gets terminated when division by zero is encountered at the run-time as
this is not a defined operation and result in run-time error. The other familiar example in case of C-
language is that of null pointer exception, which occurs when we try to access a memory location
through an un-initialized pointer. The program gets terminated in this case also.

Java has a separate construct for exception/error handling like C++. It is possible to recover from an
exception/error at run-time and continue the program exception using the exception-handling
construct.

A java exception/error is an object of class Exception/Error or one of its sub-class. JVM creates an
object of class Exception/Error or one o f their sub-class whenever exception/error occurs at
the run –time. The exception/error object contains details about the exception/error, which can be
accessed using the public methods provided for this purpose.

The are two immediate sub classes of class Throwable:


1. Error
2. Exception
Exception is the runtime error. If we have not specified a semi-colon, not declared a variables etc..
Then these all errors at being notified the complier, so these are known as the compile time error
But, if we divide a number by zero, if we access an element in an array outside its bound then an
exception is occurred, and this all will occur at the run-time

PROGRAM-
class ExceptionDemo1
{
public static void main(String args[ ])
{
int a=Integer.parseInt(args[0]);

BMB Projects ‘N’ Training


36

int b=Integer.parseInt(args[1]);
int c;
c=a/b;
System.out.println("c="+c);
}
}

Advantage of Exception/Error Handling:


 Error-handling codes are separated from the normal program flow to increase the
readability and maintainability.
 This location of the exception/error is known exactly as entire stack trace is available to
the user. This is very helpful in debugging.
 Programmer gets a chance to recover from the error/abnormal condition.
 With java, it is not must to test if an exception/error condition happens. Adding more
error/exception simply requires adding more catch clauses, but the original program
flow need not be touched.

When Exception/Error can occur?


There are many cases where abnormal condition occurs during program execution, such as:
 The class file you want to load may be missing or in the wrong format.
 Integer division by zero
 Array index is not the valid range (i.e. from 0 to length -1)
 The file you are trying to open may not exits.
 The file string, which you want to convert to a number, is having invalid characters so
that it cannot be converted to a number.
 You want to create an object but no more memory is available

BMB Projects ‘N’ Training


37

In java for each and every exception there is a class.


The super class of all exceptions is Throwable.

Exception cl ass contains details of the exception which occurs under the normal
circumstances.
Error class contains those exceptions which do not occur under the normal circumstances e.g. stack
overflow. These exception are not handled under normal situation
Pre-Defined Classes of the Exception class:
Class Description
----------------------------------------------------------------------------------------------------------------
1. ArithmeticException This class exception occurs when we divide the
number by zero.
2. ArrayIndexOutofBoundsException This class exception occurs when we refer to
an index outside the bounds or its size (0 to
size-1).
3.ClassNotFoundException This class exception occurs when we either
create an object or reference of class , which
we have not defined or which neither occurs in
any package.

BMB Projects ‘N’ Training


38

4. StringIndexOutofBoundsException This class exception occurs when we refer to


an index outside the bounds in case of a string.

5. NegativeArraySizeException This class exception occurs when we specify a


negative value as an array size
----------------------------------------------------------------------------------------------------------------

Exception Handling Construct:


The general form of Exception Handling is:
try
{
//try block
}
catch(ExceptionType1 objectname)
{
//body of catch block
}
catch(ExceptionType2 objectname)
{
//body of catch block
}
:
:
finally
{
//body of finally block
}

try block: It contains those statements which are to be examined for exception.
catch block: It is used for handling the exceptions.
finally block : It contains those statements which are always to be executed whether or not an
exception takes place.

BMB Projects ‘N’ Training


39

PROGRAM-
class ExceptionDem1
{
public static void main(String args[ ])
{
System.out.println("In the Main block");
try
{
System.out.println("In the try block");
int a=10,b=0,c;
c=a/b;
System.out.println("Result="+c);
}
catch(ArithmeticException ae)
{
System.out.println("Exception :"+ae);
}
System.out.println("Outside the Try block");
}
}

PROGRAM-

class ExceptionDem2
{
public static void main(String args[ ])
{
System.out.println("In the Main block");
try

BMB Projects ‘N’ Training


40

{
System.out.println("In the try block");
int a=10,b=0,c;
c=a/b;
System.out.println("Result="+c);
}
finally
{
System.out.println("In the finally block");
}
}
}

PROGRAM-
class ExceptionDem4
{
public static void main(String args[ ])
{
System.out.println("In the Main block");
try
{
System.out.println("In the try block");
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
int c;
c=a/b;
System.out.println("Result="+c);
}
catch(ArrayIndexOutOfBoundsException ie)
{
System.out.println("Invalid Index");
}

BMB Projects ‘N’ Training


41

catch(ArithmeticException ae)
{
System.out.println("Divide By zero");
}
finally
{
System.out.println("Always execute");
}

}
}

PROGRAM-
class ExceptionDem6
{
public static void main(String args[ ])
{
try
{
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
int c=a/b;
System.out.println("c=" +c);
}
catch(ArithmeticException ae)
{
System.out.println("Exception :"+ae);
}
catch(Exception e)
{
System.out.println("Other Exception");
}

BMB Projects ‘N’ Training


42

}
}

Throw statement :
The throw statement is used to explicitly raise the exception .

The general form is


throw new Exceptiontype();

PROGRAM-
class ExceptionDem7
{
public static void main(String args[ ])
{

try
{
int a,b;
if(args.length!=2)
throw new ArrayIndexOutOfBoundsException();
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
int c;
if(b==0)
throw new ArithmeticException();
c=a/b;
System.out.println("Result = "+c);
}
catch(Exception e)
{

BMB Projects ‘N’ Training


43

System.out.println("Exception Is :"+e);
}
}
}

14.String:
The class String and String Buffer are part of the java.lang package.
String is a sequence of characters. But unlike many other languages that implement string as
characters arrays, java implement string as object of type string.
Implementing string as built in objects allows java to provide a full complement of features that make
STRING HANDLING CONVENIENT. aLSO STRING OBJECTS CAN BE CONSTRUCTED A
NUMBER OF WAYS, MAKING IT EASY TO OBTAIN WHEN NEEDED.
tHE STRING HANDLING.
IN THE JAVA IS DONE WITH THE HELP OF THE TWO CLASSES PRESENT IN THE
package java.lang
i. String
ii. StringBuffer

1. String: String is a sequence of character and to store them we will use the object of the String
class.
The constructors of the String class are:
(a) String()
It is the default constructor of the String class and it will create a String class object
initialized with a blank string. The general form is.
String objectname=new String();
E.g.
String s=new String();
System.out.println(s);
Output:
(No output)

(b) String(char [ ] ) :

BMB Projects ‘N’ Training


44

This constructor is used to initialise the String class object with the elements of the character array.
The general form is.
String s=new String(ch);
Where, ch is the character array.
E.g.
char ch[ ]={'B','M','B','P',’N’,’T’};
String s=new String(ch);
System.out.println(s);
output:
BMBPNT
(c) String(char [ ],int ,int )
This constructor is used to create a String class object and initialise it with the specific
group of characters from the character array. The general form is.
String(ch,index,Mchars)
Where:
ch is the character array used for the initiation of the String.
index specify the starting index position from where we want to start extracting the
characters from the character array.
Mchars specify the number of characters to be extracted from the starting index position.
E.g.
char ch[ ]={'C','o','m','p','u','t','e','r'};
String s=new String(ch,1,3);
System.out.println(s);
Output :
omp
(d) String(byte [ ])
This constructor will create a String class object and initialise it with the character
corresponding to the numeric values stored in the byte array. These numeric values are taken as
ASCII values. The general form is.
String objectname=new String(b);
Where,
b is the byte aray.

BMB Projects ‘N’ Training


45

E.g.
byte b[ ]={65,66,67,68,69,70};
String s=new String(b);
System.out.println(s);
output :
ABCDEF

(e)String(byte [ ],int,int)
This constructor is used to initialise the String class object with the specific group of the
characters corresponding to the numbers stored in the byte array. The general form is.
String objectname=new String(b,index,nchars);
E.g.
byte b[ ]={65,66,67,68,69,70,71};
String s=new String(b,1,4);
System.out.println(s);
output:
BCDE
(f) String(String)
This constructor is used to create a string class object and initialise it with another String
class object. The general form is.
String objectname=new String(String obj);
E.g.
String s=new String("computer");
System.out.println(s);
Output :
computer

String class methods:


1. charAt():

BMB Projects ‘N’ Training


46

This method is used to extract the character from a particular index position.
E.g:
String s=new String(“computer”);
System.out.println(s.charAt(2));
Output:
m

2. length():
This method is used to return the length of the string . That is , the total number of characters
present in it .
The general form is,
length()
E.g.
String s=new String("computer");
System.out.println("length="+s.length());
Output:
Length=8
Program-
Write a java program to read a string and reverse it
class Reverse
{
public static void main(String args[])
{
String s=new String(args[0]);
String rev=new String(" "); /* find the reverse of the string */
for(int i=s.length()-1;i>=0;i--)
{
rev=rev+s.charAt(i);
}
System.out.println("Reverse ="+rev);
}
}

BMB Projects ‘N’ Training


47

Program-
Write a java program to generate the following pattern
String : computer
c
co
com
comp
compu
comput
compute
computer

class Pattern
{
public static void main(String args[])
{
String s=new String(args[0]);
for(int i=1;i<=s.length();i++)
{
for(j=0;j<i;j++)
{
System.out.print(s.charAt(j));
}
System.out.println("");
}
}
}
3. indexOf(): This method is used to search a character or a string within the string.
There are two forms of this function:
indexOf(int ch)
indexOf(String s)
Where:

BMB Projects ‘N’ Training


48

ch specify the ASCII value of the character which we want to search


s will be the substring which you want to search
The function returns the index number of the first match and if no match occurs then the method
will return -1
Example:
String s="this is the very fine day";
System.out.println(s.indexOf('t'));

System.out.println(s.indexOf("that"));
System.out.println(s.indexOf("the"));
Output :
0
-1
8
There is another form also which can be used for searching the multiple occurrences of a single
character or a string.
indexOf(int ch,int sindex)
indexOf(String s,int sindex)
Where:
sindex specify the index position from where we want to start the searching
Example:
String s="this is a matrix . this is cool";
System.out.println(s.indexOf("this"));
System.out.println(s.indexOf("this",0));
System.out.println(s.indexOf("this",2));
Output:
0
0
18
Program-
Write a java program to find out the number of times a substring occurs within the string

BMB Projects ‘N’ Training


49

class Search
{
public static void main(String args[ ])
{
String s=new String("this is a this is a this is a that");
String p=new String(args[0]);
int count=0;
int position=0;
while((position=s.indexOf(p,position))!= -1)
{ count++;
position=position+p.length();
}
System.out.println("Total Occurances ="+count);
}
}

4. lastIndexOf(): This method is used to search for the character or a string within the another
string from the last character position. The general form is.
lastIndexOf(int ch)
lastIndexOf(String s)
E.g.
String s="this is a very fine day";
System.out.println(s.lastIndexOf('i'));
System.out.println(s.lastIndexOf("is"));

Output:
17
5
5. toUpperCase(): This method is used to convert the string into upper case
The general form is.
String toUpperCase()
E.g.

BMB Projects ‘N’ Training


50

String s="This Fine";


System.out.println(s.toUpperCase());
Output:
THIS FINE

6. toLowerCase(): This method is used to convert the string into lower case
The general form is.
String toLowerCase()
E.g.
String s="This Fine";
System.out.println(s.toLowerCase());
Output:
this fine

7. substring(): This method is used to extract the substring from a string


The general form is.
String substring(int sindex)
String substring(int sindex,int eindex)
Where:
sindex is the starting index position
eindex is the ending index position.
but the actuall string is extracted upto the position eindex-1
Eg.
String s="computer";
System.out.println(s.substring(3));
System.out.println(s.substring(3,6));
Output:
puter
put
8. replace(): This method is used to replace all the occurrences of a single character with some
another character, within the string.
The general form is.

BMB Projects ‘N’ Training


51

String replace(char ch1,char ch2)


Where:
ch1 is used to specify the character which we want to replace .
ch2 is used to specify the character by which we want to replace the ch1
E.g.
String s="hello";
String s2;
s2=s.replace('l','t');
System.out.println(s2);
Output:
hetto

9. toString(): This method is call when we convert any value to type String . If we want to
System.out.println(ob);
Where ob is an object of the Sample class, it will generate an error, as we have not
defined the toString() method for the class Sample
Program-
class Sample
{
int i,j;
Sample()
{
i=0;
j=0;
}
Sample(int a,int b)
{
i=a;
j=b;
}
String toString()
{

BMB Projects ‘N’ Training


52

return "i="+i+" "+"j="+j;


}
}
class SampleDemo
{
public static void main(String args[ ])
{
Sample ob=new Sample(45,56);
System.out.println(ob);
}
}
Output:
i=45 j=56

10. valueOf(): This method is used to convert the string into any other data type
The general form is.
String valueOf(double)
String valueOf(int )
String valueOf(char [ ])

11. getChars():
This method is used to extract the specific group of characters from the string and assign it into the
character array.
The general form is:
getChars(int sindex,int eindex,char t[],int position)
Where:
sindex is the starting index position .
eindex is the ending index position. Actually the string is extracted upto the
position eindex-1.
t is the target character array.
position is used to specify the index position from where the insertion will start in the target array
char t[]=new char[50];
String s="computer";

BMB Projects ‘N’ Training


53

s.getChars(3,6,t,0);
for(int i=0;i<s.length();i++)
System.out.print(t[i]);
12. concat(): This method is used for conceiting two strings
String concat(String ob)
E.g.
String s1="hello";
String s2="world";
String s3=s1.concat(s2);
System.out.println(s3);
Output:
helloworld

13. trim(): This method is used to remove the leading as well as trailing spaces from the string .
String s=" hello ";
System.out.println(s);
String s1=s.trim();
System.out.println(s1);
Output:
hello
hello

StringBuffer class:

StringBuffer class lets the user to modify the characters present within the string while String class
always returns the new String object containing the modified string and the original string remains
unchanged .

The StringBuffer class reverses the 16 additional character spaces for further advancement in the
string.
Constructors of the StringBuffer class:
a) StringBuffer(): It will create the blank string buffer class object.

BMB Projects ‘N’ Training


54

b) StringBuffer(int length): This argument will set the length of the String .
E.g.
StringBuffer sb=new StringBuffer(5);
sb="computer";
System.out.println(sb);
Output:
compu

c) StringBuffer(String s ):
where: s is the string with which we want to initialize the StringBuffer class object.
E.g.
StringBuffer sb=new StringBuffer("hello");
System.out.println(sb);
Output:
hello

Methods of the StringBuffer class

1. length(): This method will return the length of the string , that is , the number of characters
present in the string .
StringBuffer sb=new StringBuffer("Hello");
System.out.println(sb);
System.out.println(sb.length());
2. capacity(): This method returns the total allocated capacity to the StringBuffer class object i.e.
the number of characters present in it plus the extra 16 characters.
StringBuffer sb=new StringBuffer("Hello");
System.out.println(sb);
System.out.println(sb.length());
System.out.println(sb.capacity());
Output:
Hello

BMB Projects ‘N’ Training


55

5
21
3) setLength(): This method is used to set the length for the StringBuffer class object .
The general form is.
void setLength(int length)
E.g.
StringBuffer sb=new StringBuffer("computer");
System.out.println(sb);
sb.setLength(5);
System.out.println(sb);
Output:
computer
compu
4) charAt(int index):
This method is used to return the character present at the particular index position in the string
E.g.
StringBuffer sb=new StringBuffer("computer");
System.out.println(sb.charAt(3));
Output :
p

5) setCharAt(int index , int ch)


The method is used to set the character at a particular index position .
E.g.
StringBuffer sb=new StringBuffer("hello");
System.out.println(sb);
sb.setCharAt(1,'a');
System.out.println(sb);
Output:
hello
hallo

BMB Projects ‘N’ Training


56

6) getChars():
This method is used to extract the specific group of characters from the string and assign it into the
character array. The general form is:
getChars(int sindex,int eindex,char t[],int position)
Where:
sindex is the starting index position .
eindex is the ending index position.Actually the string is extracted upto the position eindex-1.
t is the target character array.
position is used to specify the index position from where the insertion will start in the target array
char t[]=new char[50];
StringBuffer sb=StringBuffer("computer");
sb.getChars(3,6,t,0);
for(int i=0;i<s.length();i++)
System.out.print(t[i]);

7) append(): This method is used to append or add the character or the string at the end of the
string . This method has two forms:
append(int ch)
append(String s)

E.g.
StringBuffer sb=new StringBuffer("Quantum");
StringBuffer s;
s=sb.append("adcom") ;
s= s.append(" is") ;
System.out.println(s);
Output:
Quantumadcom is

8) insert(): This method is used to insert the character or the string at the particular position in the
string . This method has the two different forms:
insert(int index,int ch);

BMB Projects ‘N’ Training


57

insert(int index,String s);


StringBuffer sb=new StringBuffer("computer");
sb.insert(2,'a');
System.out.println(sb);
sb.insert(2,"today");
System.out.println(sb);
Output:
coamputer
cotodayamputer

9) reverse(): This method is used to reverse the string .


StringBuffer sb=new StringBuffer("comp");
System.out.println(sb);
sb.reverse();
System.out.println(sb);
Output:
comp
pmoc

10) delete(): This method is used to delete the specific group of characters from the string .
The general form is:
delete(int sindex,int eindex)
The characters are actually deleted till the position eindex-1
E.g.
StringBuffer sb=new StringBuffer("computer");
System.out.println(sb);
sb.delete(3,6);
System.out.println(sb);
Output:
computer
comer

BMB Projects ‘N’ Training


58

11) deleteCharAt(): This method is used to delete the character at the particular index position .
The general form is:
deleteCharAt(int index)
Where:
index is the character position.
E.g.
StringBuffer sb=new StringBuffer("comp");
System.out.println(sb);
sb.deleteCharAt(2);
System.out.println(sb);
Output:
comp
cop
15. Packages:
1. Introduction:
If no package name is specified in any java file then the class is part of the unnamed package.
This requires that every class must have a unique name to avoid collision. After a while,
without some way to manage the namespace, you could run out of convenient descriptive
names for individual classes. You also need some way to be assured that the name you choose
for a class will be reasonably unique and not collide with class names chose by other
programmers. Java provides a mechanism for partitioning the class name space into more
manageable chunks. This mechanism is the package.
The package is both a naming and visibility control mechanism.
You can define class inside a package that are nor accessible by code outside that package. You
can also define class members that are only exposed to other members of the same package.
This allows your class to have intimate knowledge of each other, but not expose that knowledge
to the rest of the world.

2. Defining a package:
To create a package, include a package command as the firs statement in a java source file. Any
classes declared within that file will belong to the specified package. The package statement
defines a name space in which classes are stored. If you omit the package statement, the class
names are put into the default package, which has no name and is called un-named package.

This is the general form of package statement:


Package pkg_ name;

BMB Projects ‘N’ Training


59

Java uses file system directories to store packages. Remembers that case is significant, and
directory name must match the package name exactly. More that one file can include the same
package statement.

You can create a hierarchy of packages. To do so, simply separate each package name from the
one above it by use of a period. The general form of a multi-leveled package statement is
shown here:

Package pkg_name1 [. Pkg_name3];


A package hierarchy must be reflected in the file system of your java development system.
For example a package declared as:
Package java. Awt. Image;
Needs to be stored in java/awt/image, java\awt\image or java: awt :image on your Unix,
windows, or Macintosh file system, respectively.
A global naming scheme has been proposed to use the reverse internet domain names to
uniquely identify package.
Org.apache. tomcat
Which would be unique.
A package hierarchy represents an organization of java classes and interface. It does not
represent the source code organization of the class and interface. Each java source file (also
called compilation unit) can contain zero or more definition of classes and interfaces, but the
compiler provide a separate class file containing the java byte code for each of them. A class or
interface can indicate that its java byte code be paced in a particular package, using a package
declaration.
At most one package statement can appear in a source file, and it must be the first statement in
the unit. Note that this scheme has two consequences. First, all class and interfaces in a source
file will be placed in the same package. Secondly, several source files can be used to specify
the contents of a package.

Packages: Packages is a collection of classes. In java, there are two types of packages:

1. Pre-defined packages
2. User defined packages

1. Pre-defined packages: These packages come with the java library. Some of the packages are
listed below:

Packages Description

(i) java.lang This package is automatically imported. It contains the java


classes which we normally use e.g. String,Integer,etc.

BMB Projects ‘N’ Training


60

(ii) java.applet This package will contain the classes related to the applet
programming.

(iii) java.awt This package contains the classes which will be helpful in
creating the GUI components.

(iv) java.awt.event This package contains interfaces and classes for implementing
and handling the events

(v) java.io This package contains the classes related to reading data
from keyboard , and handling the stream. And also interacting
with the files

(vi) java.net This package contains the classes for the network and socket
programming .

(vii) java.util This package contains the classes for the common utilies
program etc.. Calendar,
Random etc..

2. User Defined packages:

In order to define your own package, we have to include the following statement as the first
statement of your program

The statement is :
package packagename;

Consider the following program ,

package p;

class Sample
{
int i,j;
public void setij(int a,int b)
{
i=a;
j=b;
}
public void show()
{
System.out.println("i="+i);
System.out.println("j="+j);
}
public static void main(String args[ ])
{

BMB Projects ‘N’ Training


61

Sample ob=new Sample();


ob.setij(6,7);
ob.show();
}
}

Step for executing the above program:


1. First create the folder with name p suppose in the d: drive, so the path will be d:\p
2. Now, save the file with the name Sample.java in the folder d:\p
3. Now, make the folder d:\p as your current directory.
Move to dos,

run----> type command.com


The following prompt will appaer.
c:\windows\desktop>_
c:\windows\desktop>d:
d:\>cd p
d:\p>

4. Now, compile the program


d:\p>javac Sample.java

5. To execute, move to its parent directory


d:\p>cd..
d:\>java p.Sample

Multiple classes in the same package:


In this case a single package contains the multiple classes.

PROGRAM-

//Save by add.java
package c.bmb;
public class add
{
private int a,b;
public add(int a,int b)
{
this.a=a;
this.b=b;
}
public double getadd()
{
return a+b;
}

BMB Projects ‘N’ Training


62

public void setadd(int a,int b)


{
this.a=a;
this.b=b;
}
}

//Save by div.java
package c.bmb;
public class div
{
private int a,b;
public div(int a,int b)
{
this.a=a;
this.b=b;
}
public int getdiv()
{
return a/b;
}
public void setdiv(int a,int b)
{
this.a=a;
this.b=b;
}
}
//Save by mul.java
package c.bmb;
public class mul
{
private int a,b;
public mul(int a,int b)
{
this.a=a;
this.b=b;
}
public double getmul()
{
return a+b;
}

BMB Projects ‘N’ Training


63

}
//Save by sub.java
package c.bmb;
public class sub
{
private int a,b;
public sub(int a,int b)
{
this.a=a;
this.b=b;
}
public double getsub()
{
return a+b;
}
}
//Save by exadd.java
import c.bmb.mul;
import c.bmb.add;
import c.bmb.div;
import c.bmb.sub;
public class exadd
{
public static void main(String[] args)
{
add c = new add(2,4);
System.out.println(c.getadd());
div c1 = new div(4,2);
System.out.println(c1.getdiv());
sub c2 = new sub(4,2);
System.out.println(c2.getsub());
mul c3 = new mul(4,2);
System.out.println(c3.getmul());
}
}

16. Interface:

Interface in java is core part of Java programming language and one of the ways to achieve
abstraction in Java along with abstract class. Even though interface is fundamental object oriented

BMB Projects ‘N’ Training


64

concept. Many Java programmers thinks Interface in Java as advanced concept and refrain using
interface from early in programming career. At very basic level interface in java is a keyword but
same time it is an object oriented term to define contracts and abstraction, this contract is
followed by any implementation of Interface in Java. Since multiple inheritance is not allowed in
Java, interface is only way to implement multiple inheritance at Type level.

 Interface in java is declared using keyword interface and it represent a Type like any Class
in Java. a reference variable of type interface can point to any implementation of that
interface in Java.

 All methods declared inside Java Interfaces are implicitly public and abstract, even if you
don't use public or abstract keyword. you can not define any concrete method in interface.
That's why interface is used to define contracts in terms of variables and methods and you
can rely on its implementation for performing job.
 Interface contains the data members and the methods prototypes.
 When we create a class using the Interface we have to make use of the implements keyword.

The general form of the interface is ,

interface interfacename
{
datatype1 item1=value1;
: :
datatype1 itemn=valuen;
returntype1 methodname1(argument list1);
: :
returntypen methodnamen(argument listn);
}

PROGRAM-
interface A
{
void m1();
}

class B implements A
{
public void m1()
{

System.out.println("B class implementation");


}
}

BMB Projects ‘N’ Training


65

class InterDemo
{
public static void main(String args[ ])
{
B ob=new B();

ob.m1();
}
}

Inheritance in the Interfaces:

interface A
{
void m1();
}
interface B extends A
{
void m2();
}
class C implements B
{
public void m1()
{
System.out.println("Method M1");
}
public void m2()
{
System.out.println("Method M2");
}
}
class InterDemo2
{
public static void main(String args[ ])
{
C ob=new C();

ob.m1();

ob.m2();

BMB Projects ‘N’ Training


66

}
}

Multiple Inheritances:

interface A
{
void m1();
}
interface B
{
void m2();
}
interface C extends A,B
{
void m3();
}
class D implements C
{
public void m1()
{
System.out.println("Method M1");
}
public void m2()
{
System.out.println("Method M2");
}
public void m3()
{
System.out.println("Method M3");
}

}
class InterDemo3
{
public static void main(String args[ ])
{
D ob=new D();

ob.m1();

BMB Projects ‘N’ Training


67

ob.m2();

ob.m3();
}
}

BMB Projects ‘N’ Training

You might also like