0% found this document useful (0 votes)
3 views

Second Unit

This document provides an overview of classes, objects, methods, and inheritance in Java. It explains how to define classes, create objects, declare methods, and utilize constructors, along with concepts like method overloading and overriding. Additionally, it covers static members, nesting methods, and different forms of inheritance, including single and multilevel inheritance.

Uploaded by

iamavp1234
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Second Unit

This document provides an overview of classes, objects, methods, and inheritance in Java. It explains how to define classes, create objects, declare methods, and utilize constructors, along with concepts like method overloading and overriding. Additionally, it covers static members, nesting methods, and different forms of inheritance, including single and multilevel inheritance.

Uploaded by

iamavp1234
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

UNIT III

Classes, Objects and Methods

Class

1. Java is a true object oriented programming language. Anything we wish to represent must
be encapsulated in a class.
2. A class can be defined as a template/blue print that describes behavior/ state of its
objects.
3. Classes packs together a group of logically related data items and functions that operate
on them.
4. Data item are called fields and functions are called methods.
5. Calling specific method is known as sending the object, a message.

Defining a class

 Class is a user defined data types with a template that defines its properties.
 Similar data type declarations, we can create variables of class type.
 These variables are called instances of class or objects.

Syntax:

Class username[extends superclassname]


{
[fiels declaration]
[method declaration]
}
 Class name and super class name are any valid java identifiers
 Keyword extends tells that properties of super class name is derived by classname, what
is known as inheritance.
 Everything given in square brackets ([]) are optional.
 No semicolon is given at the end of class definition C++.

Field declaration

 Data fields are placed inside the body of class definition through variable declarations.
 They are created whenever an object instantiated. Hence they are called as instance
variables.
 Instance variables are declared the same way as we declared local variables.
 Instance variables are also known as member variables.

1
Example

Class Time {
int hours;
int minutes;
int seconds;
}
The class Time contains three integers type instance variables .The declaration can be written in
single line as :
int hours, minutes, seconds;

Methods declarations:

 A class with only data field has no life. They can’t respond message.
 Methods must beaded to the class to manipulate the data in the class;
 Methods are declared inside the body of the class after field declarations.
 Instance variables are accessible to the methods

Syntax

Type method name(parameter-list)


{
Method body;
}
There are four parts in methods declaration.

Method name: name of the method

type - Type of value it returns. It can be any data type such as int, float etc. It is void, if the
method does not return any value.

parameter-list list of parameter separated by comma. Which are passed to it. Eachparameter
should be given with its data types.

Method body : body of the method in braces {}. Which describes the operations to be
performed on dat.

Example:

Class nu
{int a,b;
void sum()
{ int c;
c=a+b;
System.out.println(c);}
2
int getdata()
{
return a;
}
}
Class Time
{
int hours, minutes, seconds;
int settime(int h; int m; int s)
{
hours=h;
minutes = m;
seconds = s;
}
}
Method set time initializes the data fields hours, minutes and seconds with values h,m and s
passed to it.
class rectangle
{
int length, width;
void setdata (int x, int y)
{
length = x;
width = y;
}
int rectarea()
{
int area;
area = length * width;
return area;
}
}

Set data methods set the values for length and width fields and rectArea method computes area
and return the results.

Creating objects

 Creating a object is known as instantiation.


 An object is a block memory space allocated of instance variables.

3
 New operator creates an object and return a reference to the object in object variables
 Any number of object can be created for a class.
 Each object has its own copy of instance variables.
 Two or more references can be created for the same object.

Example :

Rectangle r1;

r1 = new rectangle();

Here, variable r1 is an object of rectangle class. The two statement given above can be combined
into one as shown below;

rectangle r1 = new rectangle();

rectangle r1 = new rectangle();

rectangle r2 = r1;

Here, r2 and r1 refer to the object;

Accessing class members:

 Data members (fields) or function members (methods) of aclass can be accessed using
object name.
 All the member should be given value before they are used,
 Methods are called with object with name,dot operator, method name and actual values
of its parameters, if any.

Constructors

Java supports a new type of methods, called a constructor. Thar enables an object to initialize
itself when its created.

 Every class has constructors.


 If do not explicitly write a constructor for a class the java compiler builds a default
constructor for that class.
 Each time a new object is created, at least one constructor will be invoked.
 A class have more than one .0constructor(constructor overloading).

4
Rules for writing constructor:

o They should be as same name of class name.


o They should not have the return type , not even void.

Example:

class Rectangle
{

int length, width;


Rectangle(int x, int y)
{
length = x;
width = y;
}
int rectarea()
{
int area;
area = length * width;
return area;
}
}

In main() method of another class (RectangleTest) we can declare objects for Rectangle class and
initialize the data members using the constructor.

Class RectangleTest
{
public static void main(String args[])
{
Rectangle r1=new Rectangle(15,20); // constructor is called
int a1;
a1= r1. rectarea();
System.out.println(“Area of Rectangle =” +a1);
}
}

Methods overloading:

 Creating more than one method with same name, but different parameters list and
different definition is called overloading.
 Method overloading perform similar tasks, but using different parameters

5
 Java executes the right methods by matching the parameter list.
 This method is known as polymorphism.

Rule:

o The different may be in number of parameters of data type of parameters but not in
return type alone.
o i.e parameter list should be unique.
o Return type does not play any role in overloading.
o Any method can be overloaded including constructor.

Example 1: In this example, add method is overloaded with different types of parameters.

int add(int a, int b)

{
int c;
c=a+b;
return c;
}
float add(float a, float b)
{
float c;
c=a+b;
return c;
}
long add(long a, long b)
{
long c;
c=a+b;
return c;
}
Example 2: in this example, line method is overloaded to draw lines of different characters and
length. Number and type of parameters are different.

void line()
{
int i;
c=’-‘;
for(i=1;i<=30;i++)
System.out.print(c);
}
void line(int x)
{
int i;
c=’-‘;

6
for(i=1;i<=x;i++)
System.out.print(c);
}
void line(char c)
{
int i;
for(i=1;i<=30;i++)
System.out.print(c);
}
void line(int x, char c)
{
int i;
for(i=1;i<=x;i++)
System.out.print(c);
}
Calling the function with object O takes the following forms:

O.line(); // which draw a line of 30 hyphens

Output: -------------------------------------

O.line(50); // which draw a line of 50 hyphens.Here, length is passed as parameter

Output: ---------------------------------------------------------

O.line(*); // which draw a line of 30 *s, Here, the character is passed as parameter

Output: *********************************

O.line(40,’+’); // which draw a line of 40 +s. Here both length and character passed as parameter

Output: +++++++++++++++++++++++++++++++++++++++++

Example 3: Contructor can be overloaded

Class Num
{
Int A,B;
Num()
{
A=0;
B=0;
}
Num(int x, int y)
{
A=x;

7
B=y;
}
Num(int x)
{
A=x;
B=x;
}
/* Other methods */
……………
class NumTest
{
public static void main(String args[])
{
Num n1=new Nu0m(); //calls first version of the constructor
Num n2=new Num(5,3); //calls second version of the constructor
Num n3=new Num(9); //calls third version of the constructor
}
}

Static members

 Every time a class in instantiated (an object is created) a new copy of all the
members are created.
 They are called instance variables and instance methods.
 They are accessed using a object with dot operator.
 Static members (data and methods )of class are all common to all the objects.
 Static data members are declared with static keyword.
 They are called as variable and class methods.
 They re accessed using class variables and class methods.
 They are accessed using class name rather than its object name.
 Java creates only one copy of static variables.

Examples:

static int count();

static int max(int x,int y);

Rules:

 Static methods can use static data only.


 Static methods can call other static methods only.
 They can’t refer to this or super.

8
Example:

class StaticTest

static int add(int x,int y)

return x+y;

In main method, we can have the following code:

int sum=StaticTest.add(5,4);

Nesting of methods:

 A method is inside class can call another method in the same class. This is known as
nesting of methods.
 A call method call another method. i.e method1 can call method2 and method2 in turn
can call method3 and so on.

Example:

class Num
{
inta,b,c;
Num(intx,int y) // constructor
{
a=x;
b=y;
}
void add()
{
c=a+b;
display(); // call to another method in the class
}
void subtract()
{

9
c=a-b;
display(); // call to another method in the class
}
display()
{
System.out.println(a);
System.out.println(b);
System.out.println(“Result=”+c);
}
}
Here the display function is used to display the values of a,b and c. it is called by both add and
subtract methods.

Inheritance:

 The mechanism of deriving a new class old one is called inheritance.


 The old class is known as super class or base class or parent class.
 The new class is known as sub class or derived class or child class.
 Inheritance allows subclasses to inherit the variables and methods of their parent classes.
 Advantage of using inheritance are : Reusability and extensibility.
 Classes defined with useful functionality can be reused without writing them all over
again.
 Subclasses can have their properties and methods in addition to base class properties and
methods. It is known as extensibility.

Different forms of inheritance:

o Single Inheritance (only one super class)


o Multiple inheritance (Several super classes)(Java does not directly supports)
o Hierarchical inheritance.
o Multilevel Inheritance (derived from derived class).

A A B A

B C B C C C

i)Single ii)Multiple iii)Hierarchical iv)Multilevel

10
A , B , C and D are Classes

Defining a sub class

A sub classs is defined as follows

class subclassname extends superclassname

variable declaration;

methods declarations;

 The keyword extends states tht the properties of the super classname are extended to the
subclassname.
 The subclass will have i9ts own variable and methods and those of the superclass as well.

Example of single Inheritance:

class Num
{
Int a,b;
Num(int x,int y) // constructor of super class Num
{
a=x;
b=y;
}
void addab()
{
int r;
r=a+b;
System.out.println(r);
}
}
class Numderived extends Num
{
int c;
Numderived(int x,int y, int z)

11
{
Super(x,y); // calls super class constructor with two parameters
c=z;
}
void addabc()
{
int r;
r=a+b+c;
System.out.println(r);
}
}

class SingleInherTest
{
public static void main(String args[])
{
Numderived n1=new Numderived(5,10,15);
n1.addab();
n2.addabc();
}
}

Output:

15

30

 Constructor in the derived class Numderived uses the super keyword to pass the values
required for superclass Num constructor.
 The object n1 of derived class is able to call the method addab of its super class but due
to inheritance.
 It is also calls its own method addabc. It is able to use the variable a and b defined in
super class due to inheritance.

Subclass constructor:

Sub class constructor is used to construct the instance variable of both sub class and
super class. Super keyword invokes the super class constructor.

Rules:

o super should be used with in sub class constructor.


o Call to super class constructor must appear as the first statement in subclass constructor.

12
o Parameter in super class must match the order and type of the instance variables declared
in super class.

Multilevel inheritance:

 Multilevel inheritance allow us to bind a chain of classes.


 It is used to derived class as super class.
For example, Class C inherits class B, B in turn Inherits Class A. i.e class C , nherits A
and B. This may be extended to any number of levels.
 Java uyses this concepts in building its class library.

A
Grand Father Super class

B
Father Intermediate super class

C
Child Sub class

Hierarchical Inheritance :

 Hierarchical Inheritance supports hierarchical design of a program


 In hierarchical design, certain features of one level are shared by many other below the
level.
 For example, all account in a bank posses certain common features.

Hierarchical classification of bank accounts:


Account

Savings
Deposit Current

Long
Short Medium

Over riding Methods:

 If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding.
 Method is defined in both superclass and subclass with same name, same arguments,
same return type but different behavior (different code);

Use of method over Riding:

13
o Method overriding is used to provode specific implementation of a method that is
already provided by its super class.
o Method overriding is used for runtime polymorphism.

Example:

class Num
{
int a;
Num(int x)
{
a=x;
}
void display()
{
System.out.println(a);
}
}
class Numderived extends Num
{
int b;
Numderived(int x, int y)
{
super(x);
b=y;
}
void display()
{
System.out.println(a);
System.out.println(b);
}
}
The method display() is overridden.

Final variable and methods:

 All the methods and variables can be overridden by default in subclasses.


 To prevent from overriding by subclasses, declare them with final modifier.
 Making the method final ensures that it will never be altered in subclass.
 Making the variable final ensures that its values can never be changed.
 Final variable behaves like class-variables. They do not take up space in objects of the
class.

14
Example:

final int p = 20;


final void show_account_balance()
{
……………
}

Final class:

 Aclass that can’t subclassed (inherited) is called a final class.


 This is done for security reasons.
 Any attempt to inherit these classes will cause an error and the compiler will not
allowed it.
 Final class prevents any unwanted extensions to the class.

Example:

final class a
{
……….
}
Here A can’t be subclassed.

Finalizer Method:

 Constructor initializes an object when it is declared.


 Finalizer method is similar destructor in C++. It frees memory resource s used by objects.
 Java runs-time is an automatic garbage collection systems. It automatically free memory
resources used by objects.
 But objects may hold non-object resources such as file descriptors, window fonts etc.
Garbage collection can’t free these resources.
 finalize() method added to the class explicitly define tasks to free these resources hold by
the object.

Abstract methods and classes :

 The meaning of abstract is opposite to that of final. Abstract method always must always
be redefined in the subclass. i.e overriding is compulsory.
 Classes contain abstract methods should be declared as abstract classes.
 Abstract classes should contain abstract methods should be declared as abstract classes.
 Abstract class should containabstract methods with prototype without body(code).

Example:

15
abstract class shape
{
…..
…..
abstract void area();
…..
}
class Circle extends shape
{
float radius;
void area()
{
float a;
a = 3.14* radius * radius;
System.out.println(a);
}
}

Rules:
 Abstract classes cannot be instantiated i.e. we should not declare objects for abstract
classes .
 Abstracts methods of abstract classes must be defined in subclass.
 Abstract constructor or abstract static members cannot be defined.
 In the example given above, the method area() is not defined in abstract class Shape. It is
defined in sub class Circle.

Visibility Modifiers:
 All the members of a class are inherited by sub class, by default.
 Access can be restricted using visibility modifiers or access modifiers.
 Java provides three types of visibility modifiers: public, private and protected.

Public Access

Any variable or method is visible inside the class

 They are made visible outside the class by declaring them public.
 Variables or method declared as public is accessible everywhere in the java program.
 It is the widest possible visibility.

Example: public int count;

public void calculate()

16
{
………
………
}

Friendly Access

 When no access modifier is specified, the member defaults to a limited version of public
accessibility known as Friendly Access.
 Friendly access means the members are visible to all the classes in the package to which
it belongs.
 Public access means the members are visible to all the classes in any package.
 A package is nothing but source code file in which the class is defined.

Protected Access

 Visibility level of protected access lies in between public and friendly access
 Protected modifier makes the members visible to all its subclasses in current package as
well as in all the packages.
 Non-sub classes can’t access the protected members.

Private Access

 Private members are highly protected members


 They are accessible only within their own class.
 They can’t be inherited by subclasses, therefore not accessible by class members
 A member declared private behaves as final.

Private protected Access

A field can be declared with two keywords private and protected together.

Example: private protected int number;

 It gives visibility level in between private and protected access.


 This modifier makes the members visible in all subclasses regardless of the package they
are in.

Rules of Thumb

 Use public, if the member is to be visible everywhere


 Use protected, if the member is to be visible to subclasses in current package and other
packages.
 Use friendly access (default) i.e. no access modifiers, to make the members visible
everywhere in current package only.
17
 Use Private protected to make the members visible only in subclasses regardless of
packages
 Use private to make the members visible in its own class only and not anywhere.

Arrays, Strings and Vectors

Array

 An array is a group of homogeneous, data items stored in contiguous locations that share
a common name
 For example, an array of total marks obtained by students in an examination
 A particular students total mark is referred by writing a number called index or subscript
in square brackets after the array name.

Example: Total_Marks[3] represent the total marks of the 3rd student.

One Dimensional Array

 A list of items given a single variable name is known as array.


 Individual item in one dimensional or single- dimensional array are accessed with one
subscript
 In mathematics, subscribed variable are denoted as X1,X2,X3…Xn
 More generally as Xj where j=1..n.
 In Java, one dimensional array is represented as X[1], X[2], X[3]… X[n].
 In Java, Subscript begins with 0 as in X[0], X[1], X[2], X[3]… X[n-1].

To store 5 integer numbers, an array in Java is created as follows:

int number[]= new int[5];

Computer reserves 5 contiguous storage locations as shown below:

Number [0]

Number [1]

Number [2]

Number [3]

Number [4]

Values to array locations (elements) can be assigned as follows:

Number[0] = 20; number[1] =12; number[2] =8; number[3]=4; number[5]=15; which are
assigned to locations of the array as shown below:

18
20
12
8
4
15

The elements of an array can be used in Java programs like any other variables.

Example: big= number [0]; a=number[4]+5;

if(number[1]>big)

big= number[1];

Creating an Array

Creating an array involves three steps:

1. Declaring the array


2. Creation in Memory
3. Putting values

Array Declaration

Arrays in Java are declares in two forms:

Form 1: type arrayname[];

Form 2: type [] arrayname;

Example:

int number[]; or int[] number;

float average[]; or float[] average;

 Size of the array is not specified in declaration.

Creation in Memory

After declaration, the array is created in memory. new operator creation.

19
arrayname= new type[size];

Example:

number = new int[5];

average = new float[10];

Here number is an array having 5 locations to store integers. average is an array to store 10
floating point numbers (real).

The two steps, declaration and memory creation can be combijed into one as shown below:

Int number[] = new int[5];

Putting Values into Arrays

 Putting values into arrays is known as initialization.


 Array subscripts starts from 0 and the last location’s subscript is size-1.
 Java protects arrays from over runs and under runs.
 Trying to access a location out of boundaries generates error message.

Array initialization: arrayname[subscript] = value;

Example: number[0] = 15;

All the locations in an array can be initialized with values at the time of declaration:

type arrayname[]={list of values};

Examples: int number[]= {10,15,76,44,55};

The number of values in the list determines the size of the array.

Loops may be used to initialize large arrays:

for(i=0;i<100;i++)

number[i] =0; // all the 100 elements are initialized to zero.

Array Length: Java stores the length of an array in a variable length. We can get the size of the
array as.

size = number.length;

Two Dimensional Arrays:

20
Two Dimensional Arrays are needed to store a table of values. Two subscripts are used to refer
to a value table, namely row subscript and column subscript.

For example, the following table of values store Day-wise sales of 3 items in a departmental
store:

Item1 Item2 Item3

Day 1 220 300 520

Day2 108 130 430

Day3 250 260 460

The table contains 9 values arranged in 3 rows and 3 columns. It can be though of as a matrix of
3 rows and 3 columns. In mathematics, two subscripts are used to refer to a value in a matrix as
in Vij. Where i represents row subscripts and j represents column subscripts.

Two dimensional array for the above example is declared in Java as:

int v[][]; // declaration

v= new int v[3][3]; // memory creation

Memory representation for two dimensional array:

Column 0 Column 1 Column 2

Row 0 220 300 520

Row 1 108 130 430

Row 2 250 260 460

v[0][0] = 220; v[0][1] =300; v[0][2] =520;

v[1][0] =108;v[1][1] =130; v[1][2] =430;

v[2][0] =250; v[2][1] =260; v[2][2] =460;

Two dimensional arrays can be initialized at the time declaration as follows

int v[][] = { { 220,300,520}, {108,130,430}, {250,260,460}};

21
Each row containing values for 3 columns are given in separate braces. Comma is required after
each row.

Two dimensional array can also be initialized using nested for loops.

int v[][] = new int[3][3];

for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
v[i][j] = 0;
}
}

Here, all the elements of the array v are initialized to zero values.

Variable Size Arrays:

Java multidimensional arrays as “array of arrays.It is possible to create different number of columns for
each rowin a dimensional array as shown below.

int x[][]= new int [3][];

x[0] = new int [2];

x[1] =new int [4];

x[0]= new int [3];

Array Examples

Sorting Numbers :

importjava.io;
class sortnum
{
Public static void main(String args[])throwsIoException
{
DataInputStream ds = new DataInputStream(System.in);
System.out,printlnI(“Enter the size array”);
Int n= Integer.parseInt(ds.readLine());
Int t;
int a[]=new int[n];
System.out.println(n);
System.out.println(“Enter the elements of array”);
For(int i=0; i<n;i++)

22
{
For(int j=i+1; j<n;j++)
{
If (a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;

}
}
}
System.out.println(“Bubble Sort”);
For(int i=0; i<n;i++)
System.out.println(a[i]);
}
}

Matrix Multiplication :
// Multiplying two matrices
import java.io.*;
class matmul
{
public static void main(String args[]) throws IOException
{
DataInputStream ds= new DataInputStream(System.in);
inti,j,k;
String s;
int a[][]=new int[2][2];
int b[][]=new int[2][2];
int c[][]=new int[2][2];
// input loop for matrix a
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
System.out.println(“Enter the number of matrix a”);
s=ds.readLine();
a[i][j] = Integer.parseInt(s);
}
}
// input loop for matrix b
for(i=0;i<2;i++)

23
{
for(j=0;j<2;j++)
{
System.out.println(“Enter the number of matrix b”);
s=ds.readLine();
b[i][j] = Integer.parseInt(s);
}
}
// Initialize c matrix with 0
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
c[i][j] = 0;
}
}

//Multiply
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
for(k=0;k<2;k++)
{
c[i][j] +=a[i][k]* b[k][j];
}
}
}

//output
System.out.println(“Result of Multiplication”);
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
System.out.print(c[i][j]+” “);
}
System.out.print(“\n “);
}
}

24
Strings:

 Strings represent a sequence of character.


 The easiest way to represent a string is character array is in C and C++;
 Many string operations are defficult to perform on arrays;
 Inn java, Strings are objects of string and String Buffer Classes;
 Java string is not a character array is notNULL terminated(/0);
 Compared to C or C++, Strings Java are reliable and predictable.
 Java checks out of bounds in strings whereas C does not.

Java strings are declared created as follows :

string variablename;

variable name= new string (“abcd”);

or simply by assigning a value without using new operator as

string name =“ramana”;

length()“”function in string object returns the number of character stored in the string,

string name=(mary);

int x = name.length();

two strings can be concatenated using + operator used in arithmetic.

string s1 = “my”;

string s2 = “dog”;

string = s3 = s1 + s2;

String Array :
String array can be created to store more than one string in a single variable name like numerical
arrays.

String = names = new String[5];

Example:

import java.io.*;
class alphabetize
{
public static void main(String args[]) throws IOException
{
String n[]=new String[5];
String t;

25
DataInputStream d= new DataInputStream(System.in)
iIntp,c;
//Input loop
for(p=0;p<5;p++)
{
System.out.println(“Enter a Name”);
n[p] =d.readLine();
}
// Bubble Sorting Procedure
for(p=0;p<4;p++)
{
for(c=0;c<4;c++)
{
if (n[c].compareTo(n[c+1])>0)
{
t=n[c];
n[c]=n[c+1];
n[c+1]=t;
}
}
}
//Output loop
for(p=0;p<5;p++)
{
System.out.println(n[p]);
}
}
}
Input: MARY RAM ARUN BALU ILANGO
Output: ARUN BALU ILANGO MARY RAM

String methods:

 String classes creates strings of fixed length


 String classes defines a number of methods for manipulation of strings.
 The following shows the syntax and purpose of some of most commonly used string methods
 String created with string class is immutable. (i e) value of variable containing the
 string cant be modified. But, String methods can be applied and the results stored in another
variable is shown in the following table.

Method Purpose Example

s2=s1.toLowerCase(); Converts the all string s1 to all S1 = “ ABC” , s2 = “abc”

26
lower case.
s2=s1.toUpperCase(); Converts the string s1 to all S1 = “abc” , s2 = “ABC”
upper case
s2=s1.replace(c1,c2); Replace all ppearances of S1 = “aabbaaccaadd”
character c1 with c2 in s1 S1.replace(‘a’, ‘z’) returns the
string “zzbbzzcczzdd”
s2=s1.trim(); Removes white spaces at the S1 = “ABC ”, s2 =”ABC”
beginning and end of the
string s1.
s1.equals(s2) Returns true if s1= s2 S1= “abcd”, s2 =abcd”
Returns true
S1 = “ABCD”, s2 = “abcd”
returns false
S1.equalsIgnoreCase(s2); Returns true if s1= s2 ignoring S1 = “abcd”, s2 = “abcd”
the casre of letters returns the S1 = “ABCD”, s2 =
“abcd” returns true
S1.length(); Give the nth length of s1 S1 = “abcd” return 4 as length

S1.charAt(n); Give the nth character of s1 S1 = “abcd” s1.chartAt(0)


returns “a”.
S1.compareTo(s2); Returns 0 if s1= s2 S1 = “abc”s2 = “abc” returns 0
Returns positive number if S1 = “abc”s2 = “abc” returns
s1> s2 +ve
Returns negative number if S1 = “abc”s2 = “abc” returns -
s1<s2 ve

S1.concat(s2); Concatenates(joins) s1 and s2 S1 = “oh” s2= “god”


Returns ohgod
S1.substring(n) Returns substring from nth S1 = “I love india”
character Substring(7)
returns “india”
S1.substring(n, m) Returns substring from nth S1 = “I love india”
character upto m, not
including mth character
String.valueOf(p); Creates a string object for the
value p
p.toString() Creates a string representation
of object p.
S1.indexOf(x) Return the position of first
occurance of character x in s1.
S1.indexOf(‘x’,n) Returns the position of ‘x’
after nth position

String buffer class :


 String Buffer is a peer class of string class.

27
 String Buffer strings of flexible length
 Strings are mutable. i.e String Buffer strings can be modified in content and length
 Characters can be inserted or replaced in the middle of the string.

The following table shows frequently used methods of String Buffer class

Method Purpose Example


Ss1.charCharAt(n, ‘x’ ) Changes nth character to S1=”abcdefg”
character x. S1.setCharAt(2.’z’) returns
“abzdefg”
S1.append(s2) Appends the string s2 at the end S1 = “OH” s2 = “GOD”
of s1 S1.appends(s2) returns s1 =
“OHGOD”
S1.insert(n,s1) Insert the string s2 at the position
‘n’ of s1.
S1.setLength(n) Sets the length of the string s1 to S1= “abcd”, s1.length() is 4
n. If n<s1.length() s1 id S1.setLength(3); will set ss1 to
truncated. If n>s1.length() “abc”
additional space is added S1.setLength(6);
Will set s1 to “abcd”.
Two spaces are added

Vectors :

 Vector class is used to create generic dynami arrays in Java.


 The vector class in package java.util implements a growable array of objects.
 Similar to an array. It contains components that can be accessed using an integer index
 It can hold object of any type. Any number of array can be sorted.
 Objects stored need not be homogeneous.
 Vectors are created like arrays.

Vector intvect = new Vector();


Vector list = new vector(10);

Even if the size of specified, any number of objects can be put into a vector(growable).

Advantage of vector over array:

 Its convenient to use vectors to store objects


 Elements of a vector can be added or deleted as and when required.

Major constraints in using vector

 Vector cant store primitive data types int, float, long, char and double.

28
 Vector can store object types only.
 Primitive datatypes are to be objects using wrapper classes.

Vector class supports a number of methods to manipulate vectors. Importantones are listed in the
table given below

Method Purpose
list.addElement(item) Adds the specified item at the end of the list.
Or list is avector
list.add(item)
list.elementAt(n) Gives the name of nth element in the list
Or
list.get(n)
list.size() Give the number of objects in the list
list.removeElement(item) Removes the specified item from the list
or
list.remove(item)
list.removeElement(n) Removes the item stored in nth position of list
or
list.remove(n)

Example 1:

import java.util.*;
//ADDing and displaying elements in avector
Public class vector1
{
Public static void main(string[]args)
//create a vector object
Vector v = new Vector;
//adding elements
v.addElements(“1”);
v.addElements(“3”);
v.addElements(“5”);
//getting elements
System.out.println(“Elements in vector v”);
System.out.println(v.elementAt(0));
System.out.println(v.elementAt(1));
System.out.println(v.elementAt(2));
}
}
Output:

29
Elements in vector v
1
3
5
Example 2:

import java.util.*;
//Inserting an element before a location
public class vector2
{
public static void main(string[]args)
//create vector object
Vector v= new Vector;
//adding elements
v.addElements(“1”);
v.addElements(“3”);
v.addElements(“5”);
//insert a element in specific location
v.insertElementAt(“2”,1) ;
System.out.println(“Elements in vector after insertion at location 1”)
int I;
for(i=0;i<v.size();i++)
System.out.println(v.elementAt(i));
}
}
Output :

Elements in vector after insertion at location 1

2 Inserted Element

Example 3 :

import java.util.*;
//Removing an element at a time

public class vector3


{

30
public static void main(string[]args)
//create vector object
Vector v= new Vector;
//adding elements
v.addElements(“1”);
v.addElements(“3”);
v.addElements(“5”);

v.removeElementAt(1); //remove element at location 1


System.out.println(“After removing element at location 1”);
Int I;
for(i=0;i<v.size();i++)
System.out.println(v.elementAt(i));
}
}
Output:
After removing element at location 1
1
5
Example 4:
import java.util.*;
//Replacing an element with another element

public class vector4


{
public static void main(string[]args)
//create vector object
Vector v= new Vector;
//adding elements
v.addElements(“1”);
v.addElements(“3”);
v.addElements(“5”);

v.set(0,“9”); //replacement at location 0, i.e 1 with 9


System.out.println(“After replacing an element”);
int i;
for(i=0; i<v.size;i++)
System.out.println(v.elementAt(i));
}
}
Output:

31
After replacing an element

9 Replacing Element

Example 5:

import java.util.*;

//Copying vector into array

public class vector5


{
public static void main(string[]args)
//create vector object
Vector v= new Vector;
//adding elements
v.addElements(“1”);
v.addElements(“3”);
v.addElements(“5”);

int s= v.size;
String varray[] – new String[s]; //declare an array of size s
v.copy.Into(varray);
System.out.println(“Displaying arrayelements”);
int i;
for(i=0;i<s;i++)

System.out.printlm(varray[i]);
//Removing all the elements from vector
v.removeAllElements();
Systemout.println(v.size()); //displays size as zero
}
}

Output:
Displaying array elements
1
3

32
4
Wrapper class:

Wrapper class in java provides the mechanism to convert primitive into object type and
object into primitive type.

 Java is an object oriented language and can view everything object.


 The permitivedatatypes are not objects; they do not belongs to any class; they defined in
the language itself.
 A primitive data type (int, float, char,Boolean and double)can be converted in to an
object using wrapper classes.
 As the name says, a wrapper class wraps (encloses) around data type and given it as an
object appearance.
 Wrapper classes also include methods to unwrap the object and giveback the datatypes.
 Java,lang package contain wrapper classes.

Real life example:

The manufacturer wraps the chocolate with some foil or paper to prevent it from
pollution. The user takes the chocolate, removes throws and the wrapper, and ease it.

The following table shows primitive data types and their corresponding wrapper classes.

Primitive types Wrapper class


Boolean Boolean
Char Character
Float Float
Int Integer
Long Long

Primitive data types are converted into objecctr types by calling constructor of wrapper
classes. Object types are converted back into primitive data types using methods in wrapper
classes.

Constructor calling Method calling


Primitive int to Integer object int i=5; Integer object to primitive integer
Integer N = new Integer(i); i = N.intValue();
Primitive float to Float object Float object to primitive float
Float f = 4.5; f=R.floatValue();
Float R = new Float(f)
Primitive long to Long object Long object to primitive float
Long b= 123456789012; F=R.floatValue();
Long L = new Long(b);
Primitive double to Double object Double object to primitive double

33
Double c= 0.123456789123; C=D.doubleValue();
Double D = new Double(c);
Primitive boolean to Boolean object Boolean object to primitive boolean
Boolean b1 = true; b1 = B1.booleanValue();
Boolean B1 = new Boolean(b1);

Converting Numbers to strings with tostring() method:

String str;

Int i; long l; float f; double d;

Str = Integer .toString(i);

Str = Long.tostring(I);

Float = Float.tostring(f);

Str = Double.valueOf(d);

Converting string objects to numeric objects using valueOf() method :

i=Integer.valueOf(str);

l=Long..valueOf(str);

f=float.valueOf(str);

d=Double.valueOf(str);

Converting String objects containingnumbers to primitive Numbers using passing methods


(parse Type)

i=Integer.parseInt(str)

l=Long.parseLong(str);

Enumerated types:

 A enum type is a special data type that enables a variable to be a set of predefined
constants.
 The variable must be equal to one of the values that have been predefined for it.

34
 Common examples include compass directions (vlue of NOPRTH, SOUTH, EAST,
WEST) and the days of the week.
 Because they are constants, the names of an enum types fields are in upper case
letters.

J2SE 5.0 supports enumerated type using enumkeyword.This is similar static final constants in a
earlier versions of java, as shoen as below.

Public class Dats

Public static final int DAY_SUNDAY=0;

Public static final int DAY_MONDAY=1;

Public static final int DAY_TUESDAY=2;

Public static final int DAY_WEDNESDAY=3;

Public static final int DAY_THURSDAY=4;

Public static final int DAY_FRIDAY=6;

Public static final int DAY_SUNDAY=7;

The same coding canbe written using enum type as shown below:

enum Days

SUNDAY, MONDAY, TUESDAY.WEDNESDAY, THURSDAY, FRIDAY, SATURDAY

Advantage of using enumerated type:

 Compile-time type easily;


 Enum values can be used in switch statement;

Interfaces

 An interface in the java programming language is an abstract type used to specify an


interface that classes must implement.
 Interface is basically a kind of class.

35
 Interface can contain abstract methods and final fields. Along with abstract
methods and constants n interface may also contain default methods, static methods,
and nested types. Method bodies exist only for default methods and static methods.
 It is the responsibility of the classes that implements the interface to defines the code
for implementation of these methods.
 Interface fields are public, static and finally by default(so, use the keyword static and
final are optional). Methods are abstract methods with no body(code) defined.

The following are the three main reasons to use interface:

 It is used too achieve full abstraction


 As java does not support multiple inheritance, interface is used to achieve. Multiple
inheritance by extending interfaces.
 It can be used to achieve loose coupling.

Default interface:

Syntax:

interface InterfaceName

Variable declaration;

Methods declarations;

Here, interface is a keyword and InterfaceName is any valid java variable name.

All variables are declared as constants with keywords static final as shown below:

Static final type VariableName = value

 Methods are abstractbydefault.


 Code for the mothid is not included in the interface.
 The calss that implements that interface must define the code.

They are declared as follows

abstract return-type = MethodName(ParameterList)

36
Example:

interfaceArea

Final static float pi=3.142F;

float computer(flyoat x, float y);

void show();

Difference between class and interface:

A class is instantiated A interface cant be instantiated


A class can contain constructors An interface does not contain any constructor
A class contain instance fields An Interface cannot contain instance fields.
The only fields that can appear in an interface
must be declared both static and final.
A class can extend another class An interface is not extended by a class; it is
implemented b y a class. Interface can be
extended by another interface.

Implement Interface:

 A class implements an interface by inheriting the abstract methods of the interface;


 It is necessary to create a class that inherits the interface.
 The Keyword implements is used instead of extends.
 Any number of dissimilar classes can implement an interface.
 If a class that does not implement all the methods of the interface of becomes an abstract
class and cannot be instantiated.

Syntax:

class classname implements interfacename

Body of classame

More general form:

37
Class classname extends superclass implements interface1, interface2,……

BODY OF CLASSNAME

 A class can extend another class while implementing interfaces.


 More than one interface implemented by a class is separated by comma.

Example :

interface area

final static float pi=3.14F; //constant

final compute(float x,float y);//abstract method with out a body

class Rectangle implementsArea

public compute(float x,float y)

return(x*y);

class Circle implements Area

public compute(float x,float y)

return(pi*x*y);

38
}

class Interface Test

public static void main(String args[])

Rectangle r = new Rectangle();

Circle c = new Circle();

float result;

Area a;//Interface between variable declared

a= r; //Store object reference r in interface reference a

result = a.compute(5,8); //call top compute method of Rectangle

System.out.println(“Area of Rectangle=”+result);

a= c; //Store object reference c in interface reference a

result = a.compute(20); //call top compute method of Circle

System.out.println(“Area of circle=”+result);

Output:

Area of Rectangle = 40.0

Area of circle = 1256.0

Explanation:

 The program given above creates an interface called re, which contains a constant pi and
abstract method compute.
 The interface Area is implemented by two classes Rectangle and circle.
 Reference variable a for interface Area is created(Note that an objectis not instantiated)
 Object r and c for class Rectangle and Circle classes respectively are created.

39
 Object reference r and c are stored in a(interface reference variable) and the compute the
method is called
 Call to compute method rectangle is called when rectangle objects reference is stored in
interface reference variable.
 Call to compute method circle is called when circle objects reference is stored in
interface reference variable.

Extending Interfaces

 Like classes, interface can also be extended.


 An interface can subinterfacedfromother interfaces.
 The new subinterface will inherit all the members of the super interface as in class
inheritance.

For example, we can put all the constants in one interface and methods in the other. This will
enable to use constants in classes where the methods are not required.,

Example 1:

interface ItemConstants
{
int code=1001;
String name=”Fan”;
}

interface ItemMethods
{
Void display();
}
class Sales implements ItemConstants
{
……………..
}
class Invoice implements ItemConstant, ItemMethods

‘’’’’’’’’’’’’’

Example 2:

interface Item extends ItemConstants, ItemMethods


40
{

…………….

Interface Item Interface Item Multiple inheritance by class sales


constants Methods

Interface Item

Class sales

Example3:

Interface Item extends Item constants


Item Constants
{
Void display(); Item
}
Interface Methods extends Item Methods

Accesinginterface VARIABLES:

 Interface can be used to declare set of constants that can be used by different classes.
 This similar to creating a header file constants in C and C++.
 These constant values will be available to any class that implements that interface.

Interface Constants

{
Int rows = 10;\
Int cols=10;
Float pi=3.14F;

41
Float da_rate = 0.57F;
}

Class Matrix implements Constants

Int r= rows;

Int c=cols;

Float DA;

IntBasic_pay = 5000;

DA = Basic_pay * da_rate;

Float AREA;

Float radius =4.5;

Area = pi*radius*radius;

The four constants defined in Constants Interface are available to Matrix Class.

Package: Puttng class together

 Packages are janamesva’s way of grouping a variety of classes and / or interface together.
 Grouping isa done according to functionality
 Package are equivalent to class libraries in other languages.
 A package canbe defined as a grouping of related types (classes, interfaces, enumeratins
etc..,) providing access protection and name space management.
 Programmers can define their own packages to bundle group of classes/Interfaces, etc
 It is a good practice to group related classes implemented by you.
 Since the package creates a new namespace there won’t be any name conflict with name
in other packages.
 Using packages, it is easier to provide access control and it is also easier to locate related
classes.

Benefits of using packages :

 Programmers can define their own packages to bundle a group of classes/interfaces, etc.

42
 It is a good practice to group related classes implemented by you so that a programmer can easily
determine that the classes, interfaces, enumerations, and annotations are related.
 Since the package creates a new namespace there won't be any name conflicts with names in
other packages.
 Using packages, it is easier to provide access control
 It is also easier to locate the related classes.
Package in java are of two types:
1. Java API Package
2. User defined package
 Java Api can be used for designing user Interface.
 User defined packages can be used for handling our classes.

Java API Packages:

Java API package a large number of classes grouped in to different packages according to
functionality. The figures shows the functional breakdown of API Paackage.

JAVA

Lang util IO awt net applet

Java system(API) Packages and their classes:

The table shows the classes contained in system packages.

Package Name Contents


Java.lang Includes language support classes for primitive types, strings, math
functions, threads and exceptions. These classes are used by compiler
for its internal purpose.
Java.util Utility classes such as vectors. Hash tables, random numbers, date etc.
Java.io Input/Output support classes. They provide facilities for input/output of
data.
Java.awt Set of classes for implementing graphical user interfaces. They include
classes for windows, buttons, lists, menus and so on.
Java,net Classes for creating and implementing applets.

Using system packages:

43
Java Packages are organized in a hierarchical structure as shown below:

Java

awt
color

Graphics

font

………..

44
45

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy