You are on page 1of 35

KHK JAVA Unit-3

Inheritance
What is an inheritance? Explain types of inheritance?
Inheritance:
 The mechanism of creating a new class from an old class is called inheritance. Or
creating a new version for an existing class. Inheritance allows subclasses to inherit
all the variables and methods of their parent classes.
 In the terminology of Java, a class that is inherited is called a super class. The class
that does the inheriting is called a subclass.
 To inherit a class, we use the extends keyword. The general form of a class
declaration that inherits a superclass is
class subclass-name extends superclass-name
{
// body of class
}
 The inheritance process can not extend private members , static members , constructor
methods of super class into sub class.
 Inheritance may take different forms
1. Single inheritance
2. Multi level inheritance
3. Multiple inheritance
4. Hierarchical inheritance
5. Hybrid inheritance

Vasavi Degree College (C) www.anuupdates.org 1


KHK JAVA Unit-3

 In Java we can extend only one class at a time. That‟s why in java we can not find
multiple inheritance and hybrid inheritance.

Single Inheritance:
If the inheritance process has only one super class and one sub class (one level ) then it is
called single level or simple inheritance.
Example:
class A{
int i,j;
void showij( ){
System.out.println("i and j : "+i+" "+j);
}
}
class B extends A {
int k;
void showk( ){
System.out.println("k : "+k);
}
void sum( ){
System.out.println("i+j+k: "+(i+j+k));
}
}
class single {
public static void main ( String args [ ] ) {
B ob2=new B();
ob2.i=10;
ob2.j=20;
ob2.k=30;
System.out.println("Contents of ob2 :");
ob2.showij( );
ob2.showk( );
ob2.sum( );
}
}
Vasavi Degree College (C) www.anuupdates.org 2
KHK JAVA Unit-3

Multilevel Inheritance
A common requirement in object-oriented programming is the use of a derived class as a
super class. Java supports this concept and uses it extensively in building its class library. In
multi level inheritance the sub class may act as a super class for another sub class.
SALES
|
|
ITEMS_RATE
|
|
AMOUNT

The class SALES serves as a base class for the derived class ITEMS_RATE which in turn
serves as a base class for the derived class AMOUNT. The class ITEMS_RATE is known as
intermediate base class since it provides a link for the inheritance between SALES and
AMOUNT. The chain SALES ITEMS_RATE AMOUNT is known as inheritance path.

Example:
import java.util.*;
class SALES {
int sno;
void input (int a) {
sno=a;
}
}

class ITEMS_RATE extends SALES {


int noi,rpi;
void accept ( int a , int b) {
noi=a;
rpi=b;
}
}

Vasavi Degree College (C) www.anuupdates.org 3


KHK JAVA Unit-3

class AMOUNT extends ITEMS_RATE{


int a;
void cal_print ( ) {
a=noi*rpi;
System.out.println("Salesmen Number "+sno);
System.out.println("SalesAmount "+a);
}
}

class mlevel {
public static void main ( String args[ ] ) {
AMOUNT amt=new AMOUNT( );
System.out.println("Enter Salesmen Number,number of items,rate");
Scanner sc = new Scanner(System.in);
int a,b,c;
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
amt.input(a);
amt.accept(b,c);
amt.cal_print();
}}

Hierarchical Inheritance
Another interesting application of inheritance is to use it as a support to the
hierarchical design of a program. Many programming problems can be cast into a
hierarchy where certain features of one level are shared by many others below the
level. The common base class supplies its properties to the sub classes which below
the level.
Shape

Circle Rectangle

Vasavi Degree College (C) www.anuupdates.org 4


KHK JAVA Unit-3

class shape {
double dim1,dim2;
double area( ){}
}
class Rectangle extends shape {
Rectangle(double a, double b)
{
dim1=a;
dim2=b;
}
double area ( ) {
return dim1 * dim2;
}
}
class Triangle extends Figure {
Triangle(double a, double b) {
dim1=a;
dim2=b;
}
double area ( ) {
return dim1 * dim2 / 2;
}
}

class hierar {
public static void main ( String args[ ] ) {
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
System.out.println("Area is " + r.area( ));
System.out.println("Area is " + t.area( ));
}
}

Vasavi Degree College (C) www.anuupdates.org 5


KHK JAVA Unit-3

Explain super keyword ?


 super is the key word used to refer the super class members in the sub class.
 super has two general forms.
o The first is to call the superclass constructor.
o The second is used to access a member of the superclass that has been hidden
by a member of a subclass.
super is used subject to the following conditions:
 Super may only be used within a subclass constructor method.
 The call to superclass constructor must appear as the first statement within the
subclass constructor.
 The parameters in the super call must match the order and type of the instance
variable declared in the superclass.
Using super to Call Superclass Constructors
A subclass can call a constructor method defined by its superclass by use of the following
form of super:
super (parameter-list);
Here, parameter-list specifies any parameters needed by the constructor in the superclass.
super( ) must always be the first statement executed inside a subclass Constructor.
class Student {
int sno;
String sna;
Student (int a,String b) {
sno=a;
sna=b;
}
void display( ) {
System.out.println("Student number "+sno);
System.out.println("Student name "+sna);
}}
class Marks extends Student{
int m1,m2,m3;
Marks (int a,String b,int c,int d,int e) {
super(a,b);

Vasavi Degree College (C) www.anuupdates.org 6


KHK JAVA Unit-3

m1=c;
m2=d;
m3=e;
}
void print ( ){
display ( );
System.out.println("Total "+(m1+m2+m3));
}}
class super_demo1{
public static void main (String args [ ]) {
Marks M = new Marks(100,"hari",90,90,90);
M . print ( );
}}

Second Use for super


The second form of super acts somewhat like this, except that it always refers to the
superclass of the subclass in which it is used.

syntax: .
super member

Here, member can be either a method or an instance variable.


Example:
class A{
int i;
}
class B extends A {
int i; // this i hides the i in A
B(int m,int n) {
super.i=m; //i in A
i=n;// i in b
}
void show ( ){
System.out.println("i in superclass: "+super.i);
System.out.println("i in subclass : "+i);

Vasavi Degree College (C) www.anuupdates.org 7


KHK JAVA Unit-3

}}
class super_demo2{
public static void main ( String args[ ] ) {
B obj=new B(10,20);
obj.show( );
}}

Explain Method Overriding


A method in a subclass has the same name and type signature as a method in its
superclass, then the method in the subclass is said to override the method in the
superclass. When an overridden method is called from within a subclass, it will
always refer to the version of that method defined by the subclass. The version of the
method defined by the superclass will be hidden.
Example:
class A {
int i,j;
A ( int a , int b) {
i=a;
j=b;
}
void show( ){
System.out.println("i and j : "+i+" "+j);
}}
class B extends A{
int k;
B( int a , int b , int c) {
super(a,b);
k=c;
}
void show ( ) {
super.show ( );
System.out.println("k : "+k);
} }

Vasavi Degree College (C) www.anuupdates.org 8


KHK JAVA Unit-3

class override_demo {
public static void main ( String args [ ]) {
B obj=new B(10,20,30);
obj.show( );
}}

Explain Abstract classes with an example?


 Abstract class is class which declares the structure of a given abstraction without
providing a complete implementation of every method.
 The abstract class must have one more abstract method. It is the duty of the sub class
to implement the abstractions of super class. To declare an abstract method, use this
general form:
abstract type name(parameter-list);
 To declare a class abstract, you simply use the abstract keyword in front of the class
keyword at the beginning of the class declaration.
 We can‟t instantiate the abstract class directly by using new operator, because an
abstract class is not fully defined.
 Any subclass of an abstract class must either implement all of the abstract methods in
the superclass, or be itself declared abstract.

Example:

abstract class A {
abstract void callme( );
void callmetoo( ) {
System.out.println("This is a concrete method.");
} }
class B extends A {
void callme ( ) {
System.out.println ("B's implementation of callme.");
}}
class abst{
public static void main ( String args [ ] ) {
B b = new B();

Vasavi Degree College (C) www.anuupdates.org 9


KHK JAVA Unit-3

b.callme ( );
b.callmetoo();
}}

Explain Dynamic Binding with an example?


Binding occurs at run-time based on the type of object. Late binding is also called
dynamic binding or run-time binding. The compiler still doesn‟t know the object type,
but the method-call mechanism finds out and calls the correct method body. The late-
binding mechanism varies from language to language, but you can imagine that some
sort of type information must be installed in the objects. All method binding in Java
uses late binding unless a method has been declared final
Example:
abstract class Figure {
double dim1,dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
abstract double area( );
}

class Rectangle extends Figure {


Rectangle(double a, double b) {
super(a, b);
}
double area ( ) {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);

Vasavi Degree College (C) www.anuupdates.org 10


KHK JAVA Unit-3

}
double area ( ) {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
} }

class dyna_bind{
public static void main ( String args[ ] ) {
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure f;
f = r;
System.out.println("Area is " + f.area());
f = t;
System.out.println("Area is " + f.area());
} }

What is final keyword?


"final" is a keyword used as an access modifier. "final" can be applied to variables, methods
and classes and in each place it works (behaves) very differently.
 final variable
A final variable works like a constant of C-lang. Java does not support "const"
keyword and in its place it uses final. A final variable cannot be reassigned.
final int i1 = 9;
 final method
A final method in the super class cannot be overridden by the subclass.
final void showstatus( ) {---- }
 final class
A final class is a class which cannot be extended. This means that a final class can
not become a superclass nor have a subclass.
However, because it prevents inheritance all methods in a final class are implicitly
final, since there‟s no way to override them. So the compiler has the same
efficiency options as it does if you explicitly declare a method final

Vasavi Degree College (C) www.anuupdates.org 11


KHK JAVA Unit-3

Arrays
What is an array? Explain How to create an array?
Array:
An array is a collection similar data item arranged in a sequential order in the memory
and shares the same name. To refer to a particular location or element in the array, we
specify the name of the array and the index of the particular element in the array, the
index starts from 0 and ends with size-1. Arrays can be of any variable type. Arrays
are created on dynamic memory by JVM.
Types of Arrays:
Arrays are generally categorized into two parts as described here:
1. Single dimensional arrays.(or 1D arrays)
2. Multidimensional arrays.(or2D , 3D ,.. arrays)

One-Dimensional Arrays
A list of items can be given one variable name using only one subscript ( [ ] ) and
such a variable is called a single-subscripted variable or a one-dimensional array. To
create an array in Java, you use three steps:
1. Declare a variable to hold the array.
2. Create a new array object and assign it to the array variable.
3. Store things in that array.
Declaring Array Variables
Array variables indicate the type of object the array will hold and the name of the array,
followed by empty brackets ( [ ] ).
type arrayname [ ];
or
type [ ] arrayname;
Ex:
int a[ ];
float [ ] b;
Creation of memory locations for an array variable:
After declaring an array, we need to create it in the memory. Java allows us to create
arrays using new operator , as shown below:

Vasavi Degree College (C) www.anuupdates.org 12


KHK JAVA Unit-3

arrayname = new type[size];


a = new int[5];

When you create an array object using new, all its elements are initialized by their
default values.

We can also allocate and initialize the elements of an array in the array declaration by
following the declaration a comma-separated list of values enclosed in braces ({ and }).
For example, the declaration
int n[ ] = { 10, 20, 30, 40, 50 };
creates a five-element array with subscripts of 0, 1, 2, 3 and 4. Note that the preceding
declaration does not require the new operator to create the array object.
Accessing Array Elements
Once you have an array with initial values, you can test and change the values in each
slot of that array. To get at a value stored within an array, use the array subscript
expression:
myArray [subscript];
The myArray is the array name and subscript is index number of the element which we
want to access

Multi-Dimensional Arrays:
Multi dimensional arrays represent 2D, 3D … arrays. A two dimensional array is a
combination of two or more (1D) one dimensional arrays. A three dimensional array
is a combination of two or more (2D) two dimensional arrays.
Two Dimensional Arrays (2d array):
A two dimensional array represents several rows and columns of data. To represent a
two dimensional array, we should use two pairs of square braces [ ] [ ] after the array
name.
 We can create a two dimensional array by declaring the array first and then we can
allocate memory for it by using new operator as:
int marks[ ] [ ]; //declare marks array
marks = new int[2][3]; //allot memory for storing 6 elements.

Vasavi Degree College (C) www.anuupdates.org 13


KHK JAVA Unit-3

These two statements also can be written as:


int marks [ ][ ] = new int[2][3];
The left index specifies the row and the right index specifies the column

[0][0] [0][1] [0][2]

[1][0] [1][1] [1][2]

 We can declare a two dimensional array and directly store elements at the time of its
declaration, as:
int marks[ ] [ ] = {{50, 60, 55, 67, 70},{62, 65, 70, 70, 81}, {72, 66, 77, 80, 69} };

 To get at a value stored within a two dimensional array, use the array subscript
expression:
Arr_name [row] [col];
Three Dimensional arrays (3D arrays):
We can consider a three dimensional array as a combination of several two
dimensional arrays. To represent a three dimensional array, we should use three pairs
of square braces ( [ ] ) after the array name.
 We can declare a three dimensional array and directly store elements at the time of its
declaration, as:
int arr[ ] [ ] [ ] = {{{50, 51, 52},{60, 61, 62}}, {{70, 71, 72}, {80, 81, 82}}};
 We can create a three dimensional array by declaring the array first and then we can
allot memory for it by using new operator as:
int arr[ ] [ ] = new int[2][2][3]; //allot memory for storing 12 elements.
What is Variable Size Arrays?
This type of array is also called as “jagged array” and each row consists variable no of
columns. To allocate memory for a jagged array, you need only specify the memory
for the first dimension only. You can allocate the remaining dimensions separately.
This means you can construct arrays as you like.
Example:
int x[ ][ ]=new int [3][ ];
x[0]=new int[4];
x[1]=new int[2];
x[2]=new int[7];

Vasavi Degree College (C) www.anuupdates.org 14


KHK JAVA Unit-3

In this arrays the length of each array is under our control.

x[0][0] x[0][1] x[0][2] x[0][3]

x[1][0] x[1][1]

x[2][0] X[2][1] x[2][2] x[2][3] x[2][4] x[2][5] x[2][6]

These statements create a two-dimensional array as having different lengths.


x[0] is consists of 4 cols
x[1] is consists of 2 cols
x[2] is consists of 7 cols
How to know the no of elements in an array?
To know the no of elements in the array java provides length property which can be
used along with the array name. For example arr.length will give us the no of elements
in the array arr.

Example-1:
import java.util.*;
class arr1{
public static void main(String args[ ] ){
int a[ ]=new int[5];
Scanner sc = new Scanner(System.in);
int i;
System.out.println("Enter array elements :");
for(i=0;i<a.length;i++)
a[i]=sc.nextInt();
System.out.print("The given Elements are : ");
for(i=0;i<a.length;i++)
System.out.print(a[i] +" ");
}
}
Output:
Enter array elements :
10 20 30 40 50
The given Elements are : 10 20 30 40 50

Vasavi Degree College (C) www.anuupdates.org 15


KHK JAVA Unit-3

Example-2:
class arr2{
public static void main(String args[ ]) {
int a[ ]={10,20,30};
System.out.print("The array elements are : ");
for(int i=0;i<a.length;i++)
System.out.print(a[i] +" ");
}
}
Output:
The array elements are : 10 20 30

Example-3:
Write a program to reverse an array
import java.util.*;
class revarray {
public static void main(String args[ ] ){
int a[]= new int[5];
int i,temp;
Scanner sc= new Scanner (System.in);
System.out.println("Enter 5 elements");
for(i=0; i<a.length; i++)
a[i]= sc.nextInt();
for(i=0; i<(a.length/2); i++) {
temp=a[i];
a[i]=a[4-i];
a[4-i]=temp;
}
System.out.print("The reverse of the array : ");
for(i=0;i<5;i++)
System.out.print(a[i] + " ");
}
}

Vasavi Degree College (C) www.anuupdates.org 16


KHK JAVA Unit-3

Output:
Enter 5 elements
10 20 30 40 50
The reverse of the array : 50 40 30 20 10
Example-4
Write a program to delete a number from array of elements
import java.util.*;
class del_arr {
public static void main(String arg[ ]) {
int a[ ];
Scanner sc = new Scanner(System.in);
int i,n=0,q=0;
int ctr=0;
System.out.print("Enter no. of elements ");
n = sc.nextInt();
a= new int[n];
System.out.printf("Enter %d elements ",n);
for(i=0;i<n;i++)
a[i]=sc.nextInt();
System.out.println("Enter element to be deleted ");
q=sc.nextInt();
for(i=0;i<n;i++) {
if(a[i]==q) {
for (int k=i;k<n-1;k++)
a[k]=a[k+1];
ctr++;
} }
if(ctr==0)
System.out.println("Element not found");
else {
for(i=0;i<(n-ctr);i++)
System.out.print(a[i]+"\t");
} } }

Vasavi Degree College (C) www.anuupdates.org 17


KHK JAVA Unit-3

Output:
Enter no. of elements 5
Enter 5 elements 10 20 30 40 50
Enter element to be deleted 20
10 30 40 50

Example-5:
class Matrix{
public static void main(String args[ ]){
int x[ ][ ] = {{1, 2, 3}, {4, 5, 6} };
for (int i = 0 ; i < 2 ; i++){
for (int j = 0 ; j < 3 ; j++)
System.out.print(x[i][j] +" " );
System.out.println( );
}}}
Output:
1 2 3
4 5 6

Example-6
Write a program to perform matrix multiplication
import java .util.*;
class matrix_mul {
public static void main(String args[ ]) {
int a[ ][ ],b[ ][ ],c[ ][ ];
int m,n,o,p,s,i,j,k;
Scanner sc = new Scanner (System.in);
System.out.println("Enter first matrix dimension");
m=sc.nextInt( );
n=sc.nextInt( );
System.out.println("Enter second matrix dimension");
o=sc.nextInt( );
p=sc.nextInt( );
if(n!=o) {

Vasavi Degree College (C) www.anuupdates.org 18


KHK JAVA Unit-3

System.out.println("Matrix multiplication is not possible");


System.exit(0);
}
a= new int[m][n];
b=new int[o][p];
c= new int[m][p];
System.out.println("enter first matrix elements ");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
a[i][j]=sc.nextInt();
System.out.println("enter second matrix elements ");
for(i=0;i<o;i++)
for(j=0;j<p;j++)
b[i][j]=sc.nextInt();
for(i=0;i<m;i++){
for(j=0;j<n;j++){
for(k=0,s=0;k<o;k++)
s+=a[i][k]*b[k][j];
c[i][j]=s;
}
}
System.out.println("Resultant matrix ");
for(i=0;i<m;i++){
for(j=0;j<p;j++)
System.out.print(c[i][j]+" ");
System.out.println( );
}
}
}
Output:
Enter first matrix dimension
2 2
Enter second matrix dimension
2 2

Vasavi Degree College (C) www.anuupdates.org 19


KHK JAVA Unit-3

enter first matrix elements


1 2 3 4
enter second matrix elements
1 2 3 4
Resultant matrix
7 10
15 22

Vasavi Degree College (C) www.anuupdates.org 20


KHK JAVA Unit-3

Strings
What is a string and explain different ways to creation of strings?
Or
What is a string and explain string class constructors?
Strings represent a sequence of characters. A Java string is an instantiated object of
the String class. Java strings, as compared to C strings, are more reliable and
predictable. A Java string is not a character array and is not NULL terminated. String
is a class in java.lang package and the java strings are immutable.
Creating Strings:
1. We can declare a String variable and directly store a String literal using assignment
operator.
String str; // declaring the string type variable
Str=”Hello java”; //assign a group of characters to it
String str = “Hello java”
In this case JVM creates an object and stores “hello java” in that object. This object is
referenced by the variable “str”.
2. We can create an object to String class by allocating memory using new Operator. This is
like creating an object to any class.
String s1 = new String ("Java");
3. We can create a String by converting the character array into strings.
char arr[ ] = { 'p','r','o',‟g‟,‟r‟,‟a‟,‟m‟};
String s2 = new String (arr);
Now the String object contains the String “program”. This means all the characters of the
array are copied into the String.
4. We can also create a String by passing array name and specifying which characters we
need:
String s3 = new String ( arr, 2, 3 );
Here starting from 2nd character a total of 3 characters are copied into String s3.
5. We can also create a string object by using another string object
String s1= ”java”;
String s2= new String(s1);

Vasavi Degree College (C) www.anuupdates.org 21


KHK JAVA Unit-3

What is a String and explain some commonly used string methods?


Strings represent a sequence of characters. A Java string is an instantiated object of
the String class. Java strings, as compared to C strings, are more reliable and
predictable. A Java string is not a character array and is not NULL terminated. String
is a class in java.lang package and the java strings are immutable.
1. String concat (String str)
The “concat” method concatenates or joins two strings and returns a third string as
a result. The same concatenation can be done by using “+” operator which is
called string concatenation operator.
2. length ( )
The length of a string is the number of characters that it contains. To obtain this
value, call the length( ) method shown here:
int length( );
3. charAt()
This method returns the character at the specified location. Suppose we call this
method as s1.charAt(5) , then it gives the character at 5th index in the string s1.
Syntax:
char charAt(int where);
Here, where is the index of the character that you want to obtain.
4. compareTo(String str)
This method is useful to compare two strings and to know which string is bigger
or smaller or equal.
Syntax:
int compareTo ( String str );
Here, str is the String being compared with the invoking String. The result of the
comparison is returned and is interpreted as shown below:
Value Meaning
Less than zero The invoking string is less than str.
Greater than zero The invoking string is greater than str.
Zero The two strings are equal

Vasavi Degree College (C) www.anuupdates.org 22


KHK JAVA Unit-3

5. equals ( )
This method returns true if the two strings are same, otherwise false. This is case
sensitive.
Syntax:
boolean equals(Object str);
6. equalsIgnoreCase (String str)
Same as preceding but it performs case insensitive comparison.
Syntax:
boolean equalsIgnoreCase (String str)

7. replace (char oldchar, char newchar)


Returns a new String that is obtained by replacing all characters old char in String
with newchar.
Syn:
String replace (char original, char replacement);
8. substring (int beginIndex, int endIndex)
Returns a new String consisting of all characters from beginIndex until the
endIndex.
Syn:
String substring(int startIndex)
9. String toUpperCase()
This method converts all of the characters in this String to upper case using the
Syntax:
String toUpperCase( )
10. String toLowerCase()
This method converts all of the characters in this String to lower case
Syntax:
String toLowerCase( )

Vasavi Degree College (C) www.anuupdates.org 23


KHK JAVA Unit-3

Example:
Write a program to sort the given names in ascending order
class str_sort{
public static void main(String args[ ]) {
String st[ ]={"fortran","cobol","vb","Java","vc","basic"};
int i,j;
System.out.println("Before Sorting ");
for( i=0;i<st.length;i++)
System.out.println(st[i]);
System.out.print("\n"+"\n");
for(i=0;i<st.length;i++)
for(j=i+1;j<=st.length-1;j++)
if(st[i].compareTo(st[j])>0) {
String t=st[i];
st[i]=st[j];
st[j]=t;
}
System.out.println("After Sorting");
for(i=0;i<st.length;i++)
System.out.println(st[i]);
}}
Output:
Before Sorting
fortran cobol vb Java vc basic
After Sorting
Java basic cobol fortran vb vc

What is a StringBuffer class ? Explain its creation and its methods ?


StringBuffer
This class represents strings in such a way that their data can be modified. It means
StringBuffer class objects are mutable, and there are method provided in this class
which directly manipulate the data inside the object. we can insert characters and
substrings in the middle of a string , or append another string to the end.

Vasavi Degree College (C) www.anuupdates.org 24


KHK JAVA Unit-3

Creating StringBuffer object:


There are two ways to create a StringBuffer object and fill the object with a string.
We can create a StringBuffer object by using new operator and pass the string to the
object, as:
Syn:
StringBuffer sb = new StringBuffer ("Kiran");

We can create a StringBuffer object by first allotting memory to the StringBuffer


object using new operator and later storing the String into it as:
StringBuffer sb = new StringBuffer (30);
In general a StringBuffer object will be created with a default capacity of 16
characters. Here, StringBuffer object is created as an empty object with a capacity for
storing 30 characters. Even if we declare the capacity as 30, it is possible to store
more than 30 characters into StringBuffer.

StringBuffer class methods:


1. setLength( )
To set the length of the buffer size within a StringBuffer object
syntax:
void setLength(int len)
Here, len specifies the size of the buffer. This value must be non_negative.
2. append( )
The append( ) method concatenates the string representation of any other type of
data to the end of the invoking StringBuffer object
syntax:
StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)
3. insert( )
The insert( ) method inserts one string into another. It is overloaded to accept
values of all the simple types, plus Strings and Objects. Like append( ), it calls
String.valuesOf( ) to obtain the string representation of the value it is called
width. These are a few of its forms.
syntax:

Vasavi Degree College (C) www.anuupdates.org 25


KHK JAVA Unit-3

StringBuffer insert(int index, String str)


StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)
Here index specifies the index at which point the string will be inserted into the
invoking StringBuffer object.

What are Differences between String and StringBuffer classes


String class objects are immutable and hence their contents cannot be modified, where
as the StringBuffer class is a mutable object. So they can be modified directly.
StringBuffer class is synchronized by default.

Vasavi Degree College (C) www.anuupdates.org 26


KHK JAVA Unit-3

Vectors
Explain about Vectors in java?
Vector is a dynamic array that can hold objects of any type and any number. The
objects do not have to be homogeneous. Arrays can be easily implemented as vectors.
This class is defined in java.util package. Vectors are created like arrays follows:
Vector v1 = new Vector( ) // declaring without size
Vector v2 = new Vector(3)//declaring with size of 3 elements
A vector without size can accommodate an unknown number of items. Even when a
size specified, this can be overlooked and different no of items can be put into the
Vector. Vectors possess a number of advantages over arrays
 It is convenient to use vector to store objects.
 A vector can be used to store a list of objects that may vary in size.
 We can add and delete objects from the list as and when required.
The major limitations in using vectors are that we can‟t directly store simple data type
in a vector. We can only store objects.
Vector class Methods:
The vector class defines number methods that can be used to manipulate the vectors created.
1. addElement(object item) : This methods adds an item specified to the list at the end.
2. elementAt( int index) : This method gives the name of the item at index place.
3. Size( ) : Gives no of elements in the list present.
4. removeElementAt(int index) : Removes the item present at the index position.
5. removeElement(item) : Removes the specified item from the list.
6. copyInto(array) : Copies the entire list into another array.
7. insertElementAt (item,n) : inserts an item in a specified location in the list.
Example:
Wite a program to read some names into the vector and print them back
import java.util.*;
class vector_ex{
public static void main(String args[ ]){
Vector v= new Vector( );
Scanner sc = new Scanner(System.in);
int i;
System.out.println("enter 3 names ");

Vasavi Degree College (C) www.anuupdates.org 27


KHK JAVA Unit-3

for(i=0;i<3 ;i++)
v.addElement(sc.next( ));
System.out.println("The names are ");
for(i=0;i<3 ;i++)
System.out.println(v.elementAt(i));
}}
Output:
enter 3 names
hari giri siri
The names are
hari giri siri

Vasavi Degree College (C) www.anuupdates.org 28


KHK JAVA Unit-3

Wrapper Classes
What is a Wrapper Class and explain its methods?
Wrapper Classes are used to convert primitive data types into objects. A wrapper class
is a class whose object wraps the primitive data type. Wrapper classes are available in
java.lang package. Different applications on internet send data or receive data in the
form of objects.
Primitive Data type Wrapper class
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean

Character Class:
The Character class wraps a value of the primitive type char in an object. An object of
type character contains a single field whose type is char. We can create Character
class object as:
Character obj = new Character (ch); // where ch is a character.
Byte Class:
The Byte class wraps a value of primitive type 'byte' in an object. An object of type
Byte contains a single field whose type is byte. Constructors:
Byte (byte num)
Byte (String str)
Short Class:
Short class wraps a value of primitive data type 'short' in its object. Short class object
contains a short type field that stores a short number. Constructors are
Short (short num)
Short (String str)

Vasavi Degree College (C) www.anuupdates.org 29


KHK JAVA Unit-3

Integer Class:
Integer class wraps a value of the primitive type 'int' in an object. An object of type
Integer contains a single field whose type is int. Constructors are
Integer (int num)
Integer (String str)
Float Class:
Float class wraps a value of primitive type float in an object. An object of type float
contains a single field whose type is float. Constructors are
Float (float num)
Float (String str)
Long Class:
The Long class contains a primitive long type data. The object of Long class contains
a field where we can store a long value. Constructors are
Long (long num)
Long(String str):
Boolean class:
The Boolean class object contains a primitive 'boolean' type data. The object of Boolean class
contains a field where we can store a boolean value. Constructors are
Boolean (true);
Boolean (str);
Double Class:
Double class wraps a value of primitive type Double in an Object. Constructors are
Double (double num)
Double (String str)
Wrapper class methods:
The wrapper classes have a number of unique methods for handling primitive data
types and objects.
1. Converting primitive number to Object number
Integer intobj = new Integer(10);
Float fl_obj= new Float(10.5f);
Double dou_obj = new Double(10.5);
2. Converting Object numbers to Primitive numbers
int i = intobj . intValue( );
float f1= fl_obj . floatValue( );

Vasavi Degree College (C) www.anuupdates.org 30


KHK JAVA Unit-3

double d1= dou_obj. doubleValue( );


3. Converting numbers to strings
str = Integer. toString ( i );
str = Float . toString( f1 );
str = Double.. toString (d1);
4. Converting string objects to numeric objects
intobj = Integer. valueOf( str );
fl_obj = Float.valueOf( str );
dou_obj = Double.valueOf( str );
5. Converting Numeric strings to primitive numbers
int i = Integer.parseInt(str);
double d1= Double.parseDouble(str);

Vasavi Degree College (C) www.anuupdates.org 31


KHK JAVA Unit-3

Interfaces
What is an interface and how it is implemented, explain with an example?
An interface is basically a kind of class. Using interface, you can specify what a class must
do, but not how it does it. Interfaces are syntactically similar to classes, but they lack instance
variables, and their methods are declared without any body. An interface is defined much like
a class. This is the general form of an interface:
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
}
Example:
interface Shape
{
void area ( );
void volume ( );
static final double pi = 3.14;
}

Implementing Interfaces
Once it is defined, any number of classes can implement an interface. Also, one class can
implement any number of interfaces.

class classname [extends superclass] [implements interface [,interface...]] {


// class-body
}

If a class implements more than one interface, the interfaces are separated with a comma. The
methods that implement an interface must be declared public. Also, the type signature of the
implementing method must match exactly the type signature specified in the interface
definition.

Vasavi Degree College 32


KHK JAVA Unit-3

Example:
Write an example program for interface
interface Shape {
void area ( );
double pi = 3.14;
}

class Circle implements Shape{


double r;
Circle (double radius){
r = radius;
}
public void area ( ) {
System.out.println ("Area of a circle is : " + pi*r*r );
}
}

class Rectangle implements Shape {


double l,b;
Rectangle (double length, double breadth) {
l = length;
b = breadth;
}
public void area ( ){
System.out.println ("Area of a Rectangle is : " + l*b );
}
}

class InterfaceDemo{
public static void main (String args[ ]){
Circle ob1 = new Circle (10.2);
ob1.area ( );
Rectangle ob2 = new Rectangle (12.6, 23.55);
ob2.area ( );

Vasavi Degree College 33


KHK JAVA Unit-3

}
}
Output:
Area of a circle is : 326.68559999999997
Area of a Rectangle is : 296.73

DIFFERENCES BETWEEN CLASSES AND INTERFACES:

Classes Interfaces
Classes have instances as variables and Interfaces have instances as abstract methods
methods with body and final constants variables.
Inheritance goes with extends keyword Inheritance goes with implements keywords.
The variables can have any access specifier. The Variables should be public, static, final
Multiple inheritance is not possible It is possible
Classes are created by putting the keyword Interfaces are created by putting the keyword
class prior to class_name. interface prior to interface_name
Classes contain any type of methods. Classes Interfaces contain abstract methods.
may or may not provide the abstractions. Interfaces are exhibit the fully abstractions

Comparison between abstract class and interfaces


abstract class
 An abstract class is a class with one or more abstract methods
 An abstract class contains instance variables & concrete methods in addition to
abstract methods.
 It is not possible to create objects to abstract class by using new operator. But we can
create a reference of abstract class type.
 All the abstract methods of the abstract class should be implemented by its sub
classes. If any method is not implemented, then that sub class should be declared as
„abstract‟.
 Abstract class reference can be used to refer to the objects of its sub classes.
 Abstract class references cannot refer to the individual methods of sub classes.
 A class cannot be both „abstract‟ & „final‟.

Vasavi Degree College 34


KHK JAVA Unit-3

Interfaces
 An interface is a specification of method prototypes.
 An interface contains zero or more abstract methods. All the methods of interface are
public, abstract by default.
 An interface may contain variables which are by default public static final.
 Once an interface is written any third party vendor can implement it.
 All the methods of the interface should be implemented in its implementation classes.
 If any one of the method is not implemented, then that implementation class should be
declared as abstract.
 We cannot create an object to an interface. We can create a reference variable to an
interface.
 An interface cannot implement another interface. An interface can extend another
interface. A class can implement multiple interfaces.

Vasavi Degree College 35

You might also like