Secondunitcor (1)
Secondunitcor (1)
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:
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.
Instancevariables are accessible to the methods.
Syntax
Type methodname(parameter-list)
{
Method body;
}
There are four parts in methods declaration.
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 data.
Example:
Class nu
{
Int a,b; //field
void sum()
{
int c;
2
c=a+b;
System.out.println(c);
}
Int getdata()
{
return a;
}
}//class nu ends
class Time1
{
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 rectAreamethod computes area
and return the results.
3
Creating objects
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 r2 = r1;
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.
4
Rules for writing constructor:
Example:
class Rectangle
{
intlength, 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 (Rectangle Test) we can declare objects froRecthangle class
and initialize the data members using the constructor.
Class RectangleTest
int a1;
a1= r1;
rectArea();
5
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
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 c;
c=a+b;
return c;
float c;
c=a+b;
return c;
6
long add(long a, long t 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=’-‘;
for(i=1;i<=x;i++)
System.out.print(c);
void line(char c)
int i;
7
for(i=1;i<=30;i++)
System.out.print(c);
int i;
for(i=1;i<=x;i++)
System.out.print(c);
Output: -------------------------------------
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: +++++++++++++++++++++++++++++++++++++++++
Class Num
inta,b;
Num()
8
A=0;
B=0;
Num(int x, int y)
A=x;
B=y;
Num(int x)
A=x;
B=x;
/* Other methods */
……………
classNumTest
9
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:
Rules:
Example:
classStaticTest
staticint add(intx,int y)
returnx+y;
int sum=StaticTest.add(5,4);
10
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:
classNum
{
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()
{
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:
11
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.
A A B A
B C B C C C
variable declaration;
methods declarations;
The keyword extends states tht the properties of the super classname are extended to the
subclassname.
12
The subclass will have i9ts own variable and methods and those of the superclass as well.
classNum
{
inta,b;
Num(intx,int y) // constructor of super class Num
{
a=x;
b=y;
}
voidaddab()
{
int r;
r=a+b;
System.out.println(r);
}
}
classNumderived extends Num
{
int c;
Numderived(intx,int y, int z)
{
Super(x,y); // calls super class constructor with two parameters
c=z;
}
voidaddabc()
{
int r;
r=a+b+c;
System.out.println(r);
}
}
classSingleInherTest
{
public static void main(String args[])
13
{
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 andb 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:
Multilevel inheritance:
A
Grand Father Super class
14
C
Father Intermediate super class
Hierarchical Inheritance :
Savings
Deposit Current
Long
Short Medium
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);
Example:
classNum
{
int a;
Num(int x)
{
a=x;
}
void display()
15
{
System.out.println(a);
}
}
classNumderived 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.
Example:
finalint p = 20;
final void show_account_balance()
{
……………
}
Final class:
16
Final class prevents any unwanted extensions to the class.
Example:
final class a
{
……….
}
Here A can’t be subclassed.
Finalizer Method:
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:
17
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
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.
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.
18
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
A field can be declared with two keywords private and protected together.
Rules of Thumb
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.
19
Example: Total_Marks[3] represent the total marks of the 3rd student.
Number [0]
Number [1]
Number [2]
Number [3]
Number [4]
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:
20
12
8
4
15
The elements of an array can be used in Java programs like any other variables.
20
Example: big= number [0]; a=number[4]+5;
if(number[1]>big)
big= number[1];
Creating an Array
Array Declaration
Example:
Creation in Memory
Example:
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:
21
Putting Values into Arrays
All the locations in an array can be initialized with values at the time of declaration:
typearrayname[]={list of values};
The number of values in the list determines the size of the array.
for(i=0;i<100;i++)
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 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:
22
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:
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.
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
v[i][j] = 0;
}
}
23
Here, all the elements of the array v are initialized to zero values.
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.
Array Examples
Sorting Numbers :
importjava.io;
classsortnum
{
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++)
{
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++)
24
System.out.println(a[i]);
}
}
Matrix Multiplication :
// Multiplying two matrices
import java.io.*;
classmatmul
{
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++)
{
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++)
{
25
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 “);
}
}
Strings:
stringvariablename;
26
or simply by assigning a value without using new operator as
length()“”function in string object returns the number of character stored in the string,
string name=(mary);
int x = name.length();
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.
Example:
import java.io.*;
class alphabetize
{
public static void main(String args[]) throws IOException
{
String n[]=new String[5];
String t;
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)
27
{
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:
28
S1.length(); Give the nth length of s1 S1 = “abcd” return 4 as length
The following table shows frequently used methods of String Buffer class
29
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 :
Even if the size of specified, any number of objects can be put into a vector(growable).
Vector cant store primitive data types int, float, long, char and double.
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
30
or
list.remove(item)
list.removeElement(n) Removes the item stored in nth position of list
or
list.remove(n)
Example 1:
importjava.util.*;
//Adding and displaying elements in avector
Example 2:
importjava.util.*;
//Inserting an element before a location
public class vector2
{
public static void main(string[]args)
//create vector object
31
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 :
2 Inserted Element
Example 3 :
importjava.util.*;
//Removing an element at a time
32
System.out.println(v.elementAt(i));
}
}
Output:
After removing element at location 1
1
5
Example 4:
importjava.util.*;
//Replacing an element with another element
9 Replacing Element
Example 5:
importjava.util.*;
33
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.copyInto(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();
System.out.println(v.size()); //displays size as zero
}
}
Output:
Displaying array elements
1
3
5
0
Wrapper class:
Wrapper class in java provides the mechanism to convert primitive into object type and
object into primitive type.
34
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.
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 data types are converted into objecct types by calling constructor of wrapper
classes. Object types are converted back into primitive data types using methods in wrapper
classes.
String str;
35
Int i; long l; float f; double d;
Str = Long.tostring(I);
Str = Float.tostring(f);
Str = Double.valueOf(d);
i=Integer.valueOf(str);
l=Long..valueOf(str);
f=float.valueOf(str);
d=Double.valueOf(str);
i=Integer.parseInt(str)
l=Long.parseLong(str);
Enumerated types:
Aenum 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.
Common examples include compass directions (value of NORTH, 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 shown as below.
36
Public static final int DAY_MONDAY=1;
The same coding canbe written using enum type as shown below:
enum Days
Interfaces
37
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:
interfaceInterfaceName
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:
Example:
InterfaceArea
void show();
38
A class is instantiated A interface can not 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 by a class. Interface can be
extended by another interface.
Implement Interface:
Syntax:
Body of classame
BODY OF CLASSNAME
Example :
interface area
39
{
return(x*y);
public compute(float x)
return(pi*x*x);
Class Interfacetest
float result;
40
area a;//Interface between variable declared
System.out.println(“Area of Rectangle=”+result);
System.out.println(“Area of circle=”+result);
Output:
Explanation:
The program given above creates an interface called area, 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.
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
41
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:
interfaceItemConstants
{
int code=1001;
String name=”Fan”;
}
interfaceItemMethods
{
void display();
}
class Sales implements ItemConstants
{
……………..
}
class Invoice implements ItemConstant, ItemMethods
‘’’’’’’’’’’’’’
Example 2:
…………….
Interface Item
42
Class sales
Example3:
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 Interconstants
{
int rows = 10;
int cols=10;
float pi=3.14F;
floatda_rate = 0.57F;
}
int r= rows;
int c=cols;
float DA;
43
intBasic_pay = 5000;
DA = Basic_pay * da_rate;
float Area;
Area = pi*radius*radius;
The four constants defined in Constants Interface are available to Matrix Class.
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.
Programmers can define their own packages to bundle a group of classes/interfaces, etc.
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.
44
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
Java
45
awt
color
Graphics
font
………..
46
47