Вы находитесь на странице: 1из 83

Introduction to OOP and

Java Fundamentals

Unit 1

Syllabus
1 Review of OOP

2 Objects and classes in Java

3 Defining Classes & methods, Constructors

4 Access Specifiers, Static Members

5 Finalize method – Strings, Arrays

6 Packages, Java Documents

7 Comments

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Introduction
vKey points to be remembered
q Unlike C++, Java is a fully object oriented
language. i.e., In java, everything has to be
written inside classes.

Profound effect

Introduction
vJava Environments
q Java software is available as JDK (Java
Development Toolkit) version 1.0 or 1.1 or 1.2…
1.7

q Development environments
ØJava Workshop
ØBorland JBuilder
ØVisual Java (VJ++)
ØNetBeans
ØEclipse
ØWeb sphere etc.,

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Features
v Java Features
q Apart from object oriented it provides various
features for internet programming
1. Architectural Neutral
2. Robust
3. Reliable, Safe and secure
4. Simple and easy to learn
5. Distributed

Features
v Architectural Neutral
q Java gained huge popularity due to its platform
independence.

q It is a high performance cross platform


language

q Java programs can run on any client machine


on the internet without doing any changes in
the source code of program.

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Features
v Architectural Neutral
q Java is executed in 2 stages:
Ø it is compiled at the developers end
Ø uploaded on the server where it is
interpreted again and executed

q Java is compiled and converted to something


called byte code (.class files).

q “Byte code” is a series of instructions in the


form of bytes. These instructions are not
specific to any machine but are written for
JVM.

Features
v Architectural Neutral
q One can make the web page using HTML and call
the “.class” file inside it. This web page is then
transported over internet

q At the client side, the corresponding web page is


accessed by Java enabled web browser

q So when a web page is accessed, the java program


embedded inside the HTML document begins to
run with the help of JVM.

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Features
v Architectural Neutral
Rejected
Java Security
Program check

Class lib
loaded
Java
Compiler Interpreted

001100
Rejected
010001
101101 Exception Handled
010101
Executable code

Features
v Robust
q Most of the programs are leads to failure if there is
no focus paid on memory management or
exceptional behavior of the program.

q For Ex.: Sometimes certain exceptional conditions


like “File not found” are encountered when you
expect the file to be present.

q As a result program collapses !!!

q These issues are specially dealt in Java using


“Garbage Collection” and “Exception Handling”.

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Features
v Robust
q In garbage collection,
Ø Automatic
Ø a daemon thread is used in freeing the objects
which are not being referenced

q Through exception handling,


Ø Any unexpected behavior of the program can be
handled thro the piece of code

Features
v Reliable, Safe and Secure
q Java program is capable of being transported over
internet and running on anybody’s machine.

q Issue: But how does the receiver ensure that the


incoming program does not cause any harm?

Always don’t download the information from the known source


Cos’ it may be possible that downloaded program may access
System files & deletes the important files

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Features
v Reliable, Safe and Secure
q In order to make Java as Reliable, it does not allow
the program coming from the internet and running
in the browser easily – follows authentication –
called “Applet”

q Though the pointers introduce immense flexibility


and power in writing programs. Java has
eliminated the use of pointers completely. This
makes java programs are very safe i.e., hacking the
system resources is not there

Features
v Simple and easy to learn
q Java will be very simple once the basics of OOPs
are clear

v Powerful
q Java unleashes the its power thro the classes in
the library

q Inclusion of these classes and OOPs concept in


the program will enable the user to have flexible &
powerful program

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Features
v Distributed
q Java objects can be distributed across the internet.
These objects can be included in java program

Platform Independence

JAVA COMPILER
(translator)

JAVA BYTE CODE


(same for all platforms)

JAVA INTERPRETER
(one for each different system)

Windows 95 Macintosh Solaris Windows NT

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Java Development Kit
v Key points to be remembered
q javac - The Java Compiler
q java - The Java Interpreter
q jdb - The Java Debugger
q appletviewer - Tool to run the applets
q javap - to print the Java bytecodes
q javaprof - Java profiler
q javadoc - documentation generator
q javah - creates C header files

Java Application
v Key points to be remembered
Save the name of the file
as class name with
“.java” extension
import java.lang.*;
public class Class_name{
public static void main(String a[]){
----
- - - - needed statements- - -
----
}
}

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Java Application
v Key points to be remembered
q main() is qualified with public – so that main() is
visible outside the program – traced by compiler/
interpreter

q “static” keyword is given so that JVM can access


the main method without instantiating the class
contain main()

OOP
v Key points to be remembered
q Issues with C
q Is C++ a completely OOP?
q Why OOP
q OOP Paradigm
q Features of OOP
q OOP Concepts
Ø Class
Ø Abstraction
Ø Encapsulation
Ø Inheritance
Ø polymorphism

10

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


OOP
v Is C++ a completely OOP?
q No

q It is possible write C++ program without using


Object-oriented methodology

OOP
v Why OOP?
q Example: Assemble
Ø your own PC
Ø car

Each and every parts are reusable

11

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


OOP
v Why OOP?
q How about software
Ø Can you assemble a software application by
picking up a routine?

Ø Will your program runs after having duplicate


copy?
o For procedural language, reusability can not be done
o Have to Re-invent the wheel

OOP
v OOP Paradigm
q OOP is introduced to solve the problems of
procedural approach

q The data used in this approach can not flow freely


around the system, where attribute and behavior
of the data is tied that operate on it & protects it
from the modification from outside functions/
classes

q OOP allows decomposition of problem into objects

q OOP paradigm can be pictured as:

12

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


OOP
v OOP Paradigm Object B

Data Data
Object A
Communication
methods methods

Object C

methods

Data

OOP
v Features of OOP
q Program is divided into objects

q Emphasis is on data rather than procedure

q Data is hidden and can not be accessed by


external methods/classes

q Objects may communicate with each other thro’


methods

q New data & methods can be easily added

q Follows bottom-up approach

13

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


OOP

Procedural Programming OOP


Executes series of Problem is dealt as a
procedures sequentially collection of objects
Top-down programming Bottom-up programming
approach approach
Major focus is on Focus is on objects
procedures or functions
Reusability is not possible Data reusability is the main
feature

Data hiding is not possible Data hiding is possible by


making it into private

OOP
v OOP Concepts
q OOP is introduced to solve the problems of
procedural approach

q They are:
1. Objects
2. Classes
3. Data Abstraction & Encapsulation
4. Inheritance
5. Polymorphism
6. Dynamic Binding
7. Message Communication

14

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


OOP Concepts
v Objects
q “Object” is a basic runtime entity of object-
oriented system

q It is a instance of the class

q For example: It represents a table of data or an


item that the program has to handle
Ø Person name, bank account number etc.,

q Note: Before writing the program, a programmer


must decide what would be the needed objects in
a program.

OOP Concepts
v Class
q “Class” is a collection of Similar objects

q Examples: Train, Classroom etc.,

Train Engine, Boogies are the data members


of the class “Train”

15

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


OOP Concepts
v Class
q Class is a “Blue print” that says how to build an
object

q In a class, set of needed data members & the code


to handle the data can be enclosed within a class
of user defined type.

q Once the class is created, one can add new data


members belongs to that class

OOP Concepts
v Class
Prototype

class class-name {

//members of a class
public static void main(String s[ ]){
// - - - -
// needed statements
// - - - -
}

};

16

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Class Vs. Object
v Class
q Class is a “Blue print” that says how to build an
object
q It defines state placeholders and behaviors
common to all the objects

v Object
q Runtime entity
q It can be instantiated (created) from the class

Class Vs. Object


v Key points to be remembered
q To create an instance of the class, use the “new”
operator followed by the invocation of constructor

Ex:
test t1 = new test();

Returns the reference to the newly created object

17

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Class Vs. Object
v Key points to be remembered
q To access the object of the class, use the “.”
notation followed by the invocation of constructor

Ex:
test t1 = new test();
t1.name=“Third CSE B”;
t1.total=57;
t1.display();

Examples
v Do it yourself
1. Write a simple java Program to print “name and
age of the person”

2. Program to find area of circle

3. Program to compute arithmetic operations

4. Program to compute length & perimeter of


rectangle

18

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Abstraction
v Key points to be remembered
q It is the act of representing essential features
without including the background details or
explanations

q It is the process of extracting needed details and


excluding the unwanted details for the program

q Example: Getting a car driving license

Encapsulation
v Key points to be remembered
q Striking feature of OOP
Insulated data

q Enclose all in a single unit

q Wrapping up of data and methods into a single


unit is called “encapsulation”

q It is the process of binding the data and functions


in a single unit

q Encapsulation enables data hiding

19

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Encapsulation
v Key points to be remembered
q Encapsulated data (private) can not be easily
accessible by other methods/ functions. Only
those functions wrapped in the class can access it

q i.e., an object will have both data & methods in a


single unit

q Example?

Inheritance
v Key points to be remembered
q It is the process of sharing attributes and
operations among classes based on a hierarchical
relationship

q It is the process by which objects of one class


acquire the properties of objects of another class.
It supports the concept of hierarchical
classification.

q Facilitates “reusability” since all the attributes and


behavior of the main class are available to its
subclass & new features can be included

20

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Inheritance
v Key points to be remembered
q Java supports only Single Inheritance and Multiple
Interfaces

q It uses “extends” keyword for inheritance

Inheritance
v Example 1
q Assume you have 2 classes namely A and B.

q Inheritance is a mechanism which allows a class A


to inherit the properties of a class B. We say “A
inherits from B”
Ø Thus objects of class A will have access to
attributes & methods of class B without need to
redefine them

q If class A inherits from B, then B is referred as


“Super class” of A. And A is referred as
“Subclass” of B

21

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Inheritance
v Example 1
q Super classes are also referred as “Parent Class”
or “Base Class”

q Sub class is also referred as “Child Class” or


“Derived Class”

Inheritance
v Example 2
q Consider a company dealt with the hardware.
Assume this item is classified into 3 sub-classes
namely Printer, Stationery and floppy disk

q Now all the sub-classes have common attributes


such as: itemno, description, rate and reorder
level.

22

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Inheritance
Item
v Example 2
Itemno
Description
Rate
reorderlevel

Printer

Type Capacity
Size
Pagesperminute Size
Stationery Floppy disk

Polymorphism
v Key points to be remembered
q Important feature of OOP

q It’s a greek term that means “the ability to take


more than one form”

q It is the ability of a method or an operation to


behave differently for different objects

q Example 1: Behavior of a student with friends &


teachers

23

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Polymorphism
v Example

Item No: 1000051


Description: HP Printer
Printer Rate: Rs.10,500
Type: Laser
Pages per min: 8

show

Item No: 1001151


Description: 3M FD
Floppy Disk
Rate: Rs.215
Capacity: 1.44 MB
Size: 3.5 inch

Polymorphism
v Key points to be remembered
q It allows an entity to take a variety of
representations

q Extensively used in implementing Inheritance

24

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Polymorphism
v Key points to be remembered
Shape

Draw()

Circle object Box object Triangle object

Draw(Circle) Draw(box) Draw(triangle)

A single function name can be used to handle different arguments. i.e.,


Using a single function name to perform various types tasks is referred
As “Function Overloading”

Dynamic Binding
v Key points to be remembered
q “Binding” is the process of linking a procedure
call to the code to be executed in response to the
call.
q 2 types:
1. Static Binding
2. Dynamic Binding

q Dynamic binding is also referred as “Late Binding”

q It means the code associated with the given


procedure call is not known until the time of the
call at runtime

25

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Dynamic Binding
v Key points to be remembered
Shape

Draw()

Circle object Box object Triangle object

Draw(Circle) Draw(box) Draw(triangle)

Each object has its own draw() method. For every successive invocation
the draw() will be refined for each class. During run time,
the code matching the object under the current reference will be called

Message Passing
v Key points to be remembered
q An OOP allows the user to create a program with
objects

q Message Passing facilitates the communication


between objects. i.e., object can communicate with
one another by sending and receiving information

q Example:

compute.add(10,20);

26

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


OOP - Applications
v Key points to be remembered
q OOP is a one of programming buzzword using
which one can solve any type of complex
problems

q Applications
Ø Real Time Systems
Ø Simulation and Modeling
Ø Object Oriented databases
Ø Hypertext, Hypermedia and expertext
Ø AI and Expert Systems
Ø Neural Networks and parallel Programming
Ø CIM/CAD system

Classes & Objects


v Class
q Collection of similar objects

q It has data members and the methods that act


upon these data members

q It is a User defined data type. It should be viewed


as template thro the use of “Object”

27

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Classes & Objects
v Class
General Form
class class-name{
type1 data1;
:
typeN dataN;
return-type method1([argList1]){

}
:
:
}

Classes & Objects


v Class Creation
q Keyword “class” indicates the name of the class
being declared – should follow the naming
conventions of identifiers

q data1 . . .dataN are the needed data members of


the class

q method1 . . methodN are the methods / functions


used to handle those data members

q Example: area and perimeter of rectangle

28

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Classes & Objects
v Class Creation
Example
class rectangle{
int length;
int width;

int area(){
return length * width;
}
int perim(){
return 2 * (length + width);
}
}

Classes & Objects


v Object Creation
q It is a instance of a class that retains the structure
and behavior of the class

q Instance of the class can be created as similar to


that of normal variable declaration. Such variables
are called “object / instance” of the class.

q Instantiation: The process of creating a new object


for a class is known as “Instantiation”

29

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Classes & Objects
v Object Creation
q Instance of the class can be created by new
operator

rectangle r1=new rectangle();

o Causes the creation of object of type “rectangle” & returns reference


to that object
o “r1” is the object variable – that has structure & behavior of the class

Classes & Objects


v Note
q All the classes in the Java Library are start with
“Uppercase” letters

q All the methods and objects start with “lowercase”


letter

30

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Classes & Objects

Classes Objects
System out
String println
DataInputStream readLine
InputStreamReader readInt

Example

Java Program Structure

Documentation Section Suggested


Package statements Optional
Import statements Optional
Interface statements Optional
Class definitions Optional
main method class{
main method definition Essential
}

31

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Java Primaries
v Key concepts to be remembered
q This section explains:
Ø Character set
Ø Lexical Issues (Tokens)
o Identifiers
o Literals
o Keywords
o Operators
o Separators
Ø expressions

Command Line arguments


v Key points to be remembered
q Command line arguments are the parameters that
are supplied to the program during the invocation
of the program for execution.

q How do you execute a java application?

32

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Command Line Arguments
v Key points to be remembered
q Execution steps
1. Ensure that the path is been set to the
development environment
2. Compile the java application
3. Execute the java application

Command Line Arguments


v Key points to be remembered
q Execution steps
1. Ensure that the path is been set to the
development environment
Ø For Ex. Assume jdk1.6 is installed in c:\ drive
of your own system

Ø Set the path like

“set Path=%path%.;c:\jdk1.6\bin;”

in the environment variables section of the


system

33

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Command Line Arguments
v Key points to be remembered
q Execution steps
2. Compile the java application

javac filename.java

2. Execute the java application

java filename

We are not supplying any argument


as an input

Command Line Arguments


v Key points to be remembered
q If any one wants to supply the input as command
line arguments, it is essential to supply the input
during the program invocation

q Example

java filname 10 20

• Supplying the inputs


• They are considered as arguments

34

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Command Line Arguments
v Key points to be remembered
q Any argument provided in the command line
argument at the time of invocation will be passed
to the array defined in a main() method

public static void main(String s[ ] ){

Command Line Arguments


v Key points to be remembered
q Example

java filname 10 20

S [0] - 10
S [1] - 20

Example ?

35

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Command Line Arguments
v Problems
1. Convert the given Fahrenheit temperature to
centigrade temperature

2. Program that reads the radius of the circle and


compute its circumference and area

Strings
v Key points to be remembered
q String is a sequence of characters enclosed within
double quotes

q Example:

String name=“SECOND CSE B”;


String cname=“PSNACET”;

36

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Strings
v Key points to be remembered
q “String” class provides a lot of methods to
perform operations on string such as compare(),
concat(), equals(), split(), length(), replace(),
compareTo(), intern(), substring() etc.

q String is “Immutable” i.e., it can not be changed


(fixed memory allocation)

q Whenever one makes changes, new instance will


be created

Strings
v Key points to be remembered
q “String” object can be created by 2 forms
1. By using literal
2. By new key word

String name = “Second Year CSE B”

For every literal, JVM checks the memory whether


it is already assigned

If exists, it returns the reference to a object


else create the new instance & returns to the object

37

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Strings
v Key points to be remembered
q To work with String concept, String has predefined
classes & methods; {13 classes, 64 methods}

Classes

String()
String(byte bytes[ ])
String(byte bytes[ ], Charset charset)
String(byte[ ] bytes, int offset, int length, Charset charset)
String(String original)
String(StringBuffer buffer)

Strings
v Key points to be remembered

Methods
int length() int lastIndexOf(int ch)
String concat(String str) int lastIndexOf(int ch, int fromIndex)
Int indexOf(int ch) int lastIndexOf(String str)
Int indexOf(int ch, int from) int lastIndexOf(String str, int fromIndex)
Int indexOf(String str) String substring(int beginIndex)
String intern() String substring(int beginIndex, int
endIndex)
int indexOf(String str,
char[] toCharArray()
int fromIndex)
boolean isEmpty() String toLowerCase()

38

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Strings
v Key points to be remembered

Methods
int length() returns the length of this string
String concat(String str) concatenates the specified string to the end
of this string
Int indexOf(int ch) returns the index within this string of the
first occurrence of the specified character.
Int indexOf(int ch, int returns the index within this string of the
from) first occurrence of the specified character,
starting the search at the specified index.
Int indexOf(String str) returns the index within this string of the
first occurrence of the specified substring
String intern() This method returns a canonical
representation for the string object.

Strings
v Key points to be remembered

Methods
int indexOf(String str, int This method returns the index within this
fromIndex) string of the first occurrence of the
specified substring, starting at the specified
index.
boolean isEmpty() This method returns true if, and only if,
length() is 0.
int lastIndexOf(int ch) This method returns the index within this
string of the last occurrence of the
specified character
int lastIndexOf(int ch, int This method returns the index within this
fromIndex) string of the last occurrence of the
specified character, searching backward
starting at the specified index.

39

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Strings
v Key points to be remembered

Methods
int lastIndexOf(String This method returns the index within this
str) string of the rightmost occurrence of the
specified substring.
int lastIndexOf(String This method returns the index within this
str, int fromIndex) string of the last occurrence of the
specified substring, searching backward
starting at the specified index.
String substring(int returns a new string that is a substring of
beginIndex) this string
String substring(int
returns a new string that is a substring of
beginIndex, int
this string.
endIndex)

Strings
v Key points to be remembered

Methods
char[ ] toCharArray() converts this string to a new character
array.
String toLowerCase() converts all of the characters in this String
to lower case using the rules of the default
locale
String converts all of the characters in this String
toLowerCase(Locale to lower case using the rules of the given
locale) Locale.
String toString() returns the string itself

40

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Strings
v Key points to be remembered

Methods
static String returns the string representation of the char
valueOf(char c) argument.

static String returns the string representation of the


valueOf(double d) double argument.

static String returns the string representation of the float


valueOf(float f) argument.

Example?

StringBuffer
v Key points to be remembered
q “StringBuffer” is a peer class of “String” that
provides much of the functionality of strings.

q String creates the strings of fixed length but


“StringBuffer” creates flexible length that can be
modified interms of length and content

StringBuffer sb=new StringBuffer(“STRING”);

41

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


StringBuffer
v Key points to be remembered
q “StringBuffer” class is used to create a mutable
String

Constructors
StringBuffer() Creates empty String Buffer with the
initial capacity of 16
StringBuffer(String) Creates a String object with the
specified String
StringBuffer(int) Creates empty String Buffer with the
specific capacity

StringBuffer
v Key points to be remembered

Methods
setCharAt(n, ‘X’) Modifies the “n” th character to X
append(String) Appends the specified string
Inserts the specified String at nth
insert(n,String)
position
Returns the allocated capacity of
capacity()
Stringbuffer object
Returns the actual length of the
length()
string object
Set the length of StringBuffer
setLength()
object

42

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


StringBuffer
v Key points to be remembered
q “StringBuffer” class is used to create a mutable
String

Methods
reverse() Used to reverse the String
capacity() Used to return the current capacity
length() Used to return the actual length of
the string
substring()
Used to separate the String

Access Specifiers
v Key points to be remembered
q “Access Specifier” is a concept that helps one to
restrict the access to members of the class

q Offers 4 types
Ø public
Ø default (no specifier or friendly access)
Ø protected
Ø private

43

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Access Specifiers
v public
q The set of variables or functions declared as
“public” will be accessible by other parts of a
program

q One can define a class / method /variable using


“public” keyword

Access Specifiers
v public

public class test{


public static void main(String s[ ]){
public int a, b;
// Needed statements
}
}

44

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Access Specifiers
v public

public class test{


public static void main(String s[ ]){
// Needed statements
}
}

public class sample{ Error


// publicis
Class “sample” intpublic,
a, b; should be declared in a file
}
named “sample.java”
public class sample{
^

Access Specifiers
v Friendly access
q In many programs, programmer may failed to set
of variables or functions declared as “public”. At
this instant still the members will be accessible to
other classes in the program

q i.e., when no access specifier is specified, the


member defaults to the limited version of public
accessibility is known as “friendly access”

45

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Access Specifiers
v public Vs. friendly access
q “public” specifier lets the members to be visible in
all the classes, regardless of their packages

q While the “friendly access” makes the members


visible to the same package but not in other
packages

Access Specifiers
v protected
q This visibility lies between “public” and “friendly
access”

q In general it is needed when there is a inheritance


involved

q Data and function members can be accessed by


its child classes

q Non-member methods can not access the


protected data

46

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Access Specifiers
v private
q This visibility has higher degree of protection

q Members of the class will be accessible only by


the same class

q They can not be inherited. So it can not be used by


its child class

q If a method declared as private it will be used as


“final”

Access Specifiers

Private
Accessibility Public Protected Friendly private
protected
Same class Yes Yes Yes Yes Yes
Sub-class in same
Yes Yes Yes Yes No
package
Other classes in the
Yes Yes Yes No No
same package
Sub-classes in other
Yes Yes No Yes No
packages
Non subclasses in
Yes No No No No
other packages

47

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Access Specifiers
v Thumb rule

Use When
public If the field is to be visible everywhere
protected If the field is to be visible everywhere in the
current package & sub-classes in other
packages
default If the field is to be visible everywhere in the
current package
private protected
If the field is to be visible only in subclasses

private If the field is not to be visible everywhere


except its own class

Constructors
v Key points to be remembered
Data member
class personal{
String name;
int age;
void getDetails() throws Exception{
DataInputStream di = new DataInputStream(System.in);
name = di.readLine();
age=di.readInt();
}
}
class profile{
Function member
public static void main(String s[ ]) throws Exception{
personal p = new personal();
p.getDetails();
} Here, member function getdetails() can be accessed via
} the instance of class “personal” like p.getDetails() where by
Data can be assigned

48

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Constructors
v Key points to be remembered
q Here, member function of personal class is used
to assign the values to its data member

q So the values for the data member of the class can


be assigned only after the instance creation of the
appropriate class

class profile{
public static void main(String s[ ]) throws Exception{
personal p = new personal();
p.getDetails();
}
}

Constructors
v Key points to be remembered
q These functions can not be used to initialize the
member variables at the time of creation

q Example: Implementation of Stack

With reference to technical definition, some part of object


may require initialization before it can be used

49

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Constructors
v Key points to be remembered
q Java allows objects to initialize themselves when
they are created. This automatic initialization is
performed thro’ the use of a “constructor
function”

q “Constructor” is a member function or a method


that has the same name as that of class

q Note: Constructor is optional

Constructors
v Synonym
q “Constructor” is a method which are used to
initialize object automatically when the instance of
the appropriate class is created

q “Constructor” is a special member function whose


task is to initialize the objects of its class when it
is created automatically

q It is referred as constructor cos’ it constructs the


values of data member of the class

50

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Constructors
v Characteristics of a constructor:
q Name of the constructor must be same as the
name of the class for which it is being used

q It should not return a value not even a void

q They are invoked automatically when the objects


of its class is created

q They can not be inherited, though a derived class


can call the base class constructor

Constructors
v Types
1. Default Constructor
2. Parameterized Constructor
3. Copy constructor
4. Multiple Constructors in a class

51

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Constructors
v Default Constructor
q A constructor that accepts no parameters is called
“Default Constructor”

q Example: Area and perimeter of the rectangle

Constructors
v Default Constructor
class assign{ “assign()” is default constructor
double length, width; that accepts no arguments
assign(){
length=2.0;width=3.0;
}
double area(){
return ½* length * width;
}
Invokes the default constructor
}
& initialize the values
class rectangle{
public static void main(String s[ ]){
assign a=new assign();
double res = a.area();
}
}

52

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Examples
v Do it yourself
q Implement a java application using default
constructor to:
1. Compute arithmetic operations among 2
positive integers
2. Find area and perimeter of the circle
3. Compute push and pop operations in a stack
4. Compute insert and delete operations in a
Queue

Constructors
v Parameterized Constructor
q A constructor that can take arguments for its
initialization are referred as “Parameterized
Constructor”

q Example: Area and perimeter of the rectangle

53

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Constructors
v Parameterized Constructor “assign()” is a parameterized constructor
class assign{ Coz’ that takes arguments for initialization
double length, width;
assign(double l, double w){
length=l;width=w;
}
double area(){
return ½* length * width;
}
Invokes the parmeterized constructor
}
& initialize the values
class rectangle{
public static void main(String s[ ]){
assign a=new assign(2.0,3.0);
double res = a.area();
}
}

Examples
v Do it yourself
q Implement a java application using constructor to:
1. Create a class called employee that will have
the following attributes. Employee no., name,
address, dob, hiredate. The class must have the
following methods also;
a) A constructor that accepts nothing and initializes
all numeric attributes with “0” and string with null
b) A constructor that accepts all attribute values
c) A method called display() that displays all the
attributes
d) A method called changeAddress(String address)
that changes the address of an employee

54

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Examples
v Do it yourself
2. Write a program that accepts numeric command
line arguments and adds all of them. For example,
if the argument list is: 100,100,134,150,300,200

Polymorphism
v Key points to be remembered
Polymorphism

Compile Time Run Time


Polymorphism Polymorphism

Operator Function
Virtual Function
Overloading Overloading

55

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Polymorphism
v Function Overloading
q “Overloading” refers to the use of same thing for
different purposes

q Java permits overloading of functions.

q This means that one can use the same function


name to create functions that perform a variety of
different tasks

Function Polymorphism

Polymorphism
v Function Overloading
q i.e., Using the concept of “Function Overloading”,
one can design a family of functions with one
function name but with different argument list.

q Here, the function would perform different


operations depending upon the argument list in
the function call

q The correct function to be invoked is determined


by checking the number and type of the arguments
but not on the function type

56

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Polymorphism
v Function Overloading
q Here Java achieves polymorphism thro’ the use of
“Function Overloading”

q i.e., 2 or more functions can share the same name


as long as their parameter declarations are
different.

q In this situation, the functions that share the same


name are said to be overloaded and the process is
referred to as “Function overloading”

Polymorphism
v Function Overloading
q For the best illustration consider a function
“add()” can handle different types of data:

int add(int a, int b);


int add(int a, int b, int c);
double add(double x, double y);
double add(int x, double y);

Function Prototype

57

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Constructor Overloading
v Key points to be remembered
q “Constructor overloading” is a technique in which
a class can have any number of constructors that
differ in parameter lists

q Example:

test(int a, int b)
test(double a, double b)
test(double a, double b, double c)

Constructor Chaining
v Key points to be remembered
q Consider the scenario where a base class is
extended by its child class. Whenever an object of
child class is created, the constructor of parent
class will be invoked first. This is called
“Constructor chaining”

q Can be done in 2 ways


1. Within the same class – use “this()” keyword
2. Among the base / child classes – use “super()”
keyword

58

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Constructor Chaining
v Key points to be remembered: Rules
q The “this()” or “super()” should always be the first
line of constructor
q There should be one constructor without using
“this()” or “super()”
q Chaining can be achieved in any order

Example?

Copy Constructor
v Key points to be remembered
q If a constructor accepts a “reference” to its own
class as a parameter. Then it is referred as “Copy
Constructor”

q i.e., this type of constructor takes only one


parameter, which is a reference to the object of the
same class

59

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Copy Constructor
v Key points to be remembered

class classname{
classname(classname obj){
// needed statements
}
}

One class object is passed as an argument

Examples
v Do it yourself
1. Write a program to find the volume of the room
using copy constructor

60

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Array
v Key points to be remembered
q “array” is a collection of similar type of elements
that have contiguous memory location.

q Java array is an object the contains elements of


similar data type. It is a data structure where we
store similar elements. We can store only fixed set
of elements in a java array.

q Array in java is index based, first element of the


array is stored at 0 index

Array
v Key points to be remembered

61

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Array
v Key points to be remembered
q Merits
1. Code optimization – retrieve / sort the data
easily
2. Random access – can get the data at any index
position

q Demerits
1. Size is limited - one can store fixed size of
elements ; does not grow at run time

Array
v Key points to be remembered
q Types
1. Single dimensional array
2. Multi dimensional array

Arrays will have declaration, instantiation and initilalization

62

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Array
v One dimensional array
Syntax

datatype[ ] var;
or
datatype [ ]var;
or
datatype var[ ];

Array
v One dimensional array
Syntax

datatype var[ ];
var = new datatype[size];

instantiation

For initialization, use loop structure

63

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Array
v One dimensional array
Syntax

datatype var[ ]={data1, data2,..}

Declare,
instantiation and
intialize

For initialization, use loop structure

Examples
v Do it yourself: Write a program
1. To read and print the n elements using an array
2. To display the sum and average of n elements
3. To sort the given elements in ascending order

64

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Array
v Multi dimensional array
Syntax:
Declare

datatype[ ][ ] var;
or
datatype [ ][ ]var;
or
datatype var[ ][ ];

Array
v One dimensional array
Syntax:
instantiate

datatype var[ ];
var = new datatype[row][column];

instantiation

For initialization, use loop structure

65

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Array
v Multi dimensional array
Syntax:
Initialization

a[0][0]=1;
a[0][1]=2;
a[0][2]=3;
a[1][0]=4;
a[1][1]=5;
int a[ ][ ]={{1,2,3},{2,4,5},{4,4,5}};
a[1][2]=6;
a[2][0]=7;
a[2][1]=8;
a[2][2]=9;

Arrays
v Key points to be remembered
q “Arrays” is a static block – available in “java.util”
package. It permits arrays to be viewed as list

q This class has various built-in methods for


manipulating arrays like sorting / searching

Object

Arrays

66

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Arrays
v Key points to be remembered
q During the implementation of problem, one may
need to perform following tasks like:
Ø Fill an array (store)
Ø Sort an array
Ø Binary search in an array

“Arrays” class has static methods using which


one can perform above functions

Example:
int a[ ] = {10, 2, 5};
Arrays.sort(a)

Arrays
v Key points to be remembered

Methods
sort(array[ ]) Used to sort in ascending order
sort(double[ ]) Sort the array of doubles in asc. Order

sort(char[ ]) Sort the array of char in asc. Order

fill(arr[ ], obj) Fills an array with an object value

fill(double[ ], Fills each elements of double with


double) specified double value
Fills each elements of int with specified
fill(int [ ], int)
int value

67

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Static Members
v Key points to be remembered
q 2 members
1. Data member
2. Function member

Both members can be qualified with “static”

Static Members
v Key points to be remembered
Data member

class person{
char name[20];
int age;
void getdetails(void){ }
void display(void){ }
};

Function member

68

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Static Data Members
v Key points to be remembered
q Similar to the concept followed in C++.

q A variable can be declared as “static”

Static Data Members


v Characteristics of Static Data Member
q Java Instance variables are given a separate
memory for storage. If there is a need for a
variable to be common to all the objects of a single
class then the static modifier should be used in
the variable declaration.

q Static member will be stored in a permanent


memory location i.e., static storage

q Only one copy of the member is created for the


entire class & is shared by all the members of that
class

69

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Static Data Members
v Characteristics of Static Data Member
q It is visible only to that class but its lifetime is the
entire program

q If needed, the objects of the same class can


modify its static variables

q Static data member can be accessed by static


methods also.

q A constant member can also be defined with


“final” “static” key word to make it as common to
the entire program

Static Data Members


v Characteristics of Static Data Member
q When a programmer fails to initialize the static
variables, they will be initialized to default values
when the object of its class is created

q i.e.,
Ø Boolean – false
Ø Numeric – 0
Ø String – null

70

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Static Data Members
v Characteristics of Static Data Member
q Static variable can be referenced “.” operator by
any one of the following form

classname.staticvariable;
or
objectname.staticvariable;

Static Data Members


v Use of Static Data Member
q Mainly used to:
Ø Maintain values common to the entire class i.e.,
global

Ø Only one copy will be retained

Example?

71

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Static method
v Key points to be remembered
q A function or method of a class can also be
qualified with “static”

q So, it is not essential to create an object of the


class in order to invoke a static method

q Static method can be invoked in the following form

classname.staticmethodname([arguments]);
or
objectname.staticmethodname([arguments]);

Static method
v Properties of a static method
q Static method can invoke or access to only other
static members (functions /variables) declared in
the same class

q They can not refer “this” and “super” keywords

q Static method can be declared like:

static returntype methodname(parameters){


// needed statements
}

72

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


finalize method
v Key points to be remembered
q Similar to main() method, finalize() method is a
special method

q Provided by Java “Object” class used by


“Garbage Collection system”

q “finalize()” method used to check the code and


removes those objects which are not being
referred for long time i.e., reclaim the object

q It does last chance for any object resources to


perform cleanup activity

finalize method
v Key points to be remembered
q For the best illustration, consider one have written
a Java program to access database and file
system (nonobject resources).

q During the execution of program, object of java


program will be associated with these non-object
resources in the memory.

q If these access is not used for long time, the


memory occupied by these resources must be
reclaimed for other purposes

73

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


finalize method
v Key points to be remembered
q In Java, garbage collection is default but it
reclaims the memory spaces associated with the
instance objects used in the program. It will not
reclaim the nonobject references.

q To do this, use “finalize()”

finalize method
v Key points to be remembered
q Write “finalize()” method in a class if it holds one
or more nonobject resources

q Before removing these objects, java run time


environment invokes the finalize()

74

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


finalize method
v Key points to be remembered
q “finalize()” method is defined as protected in
“java.lang.Object” class. It must be overrided
when we use.

q This method is not automatically chained. It is


essential to call finalize() method of super class
explicitly.

q It is called once by Garbage collection thread


before reclaiming

finalize method
v Key points to be remembered
q Any exception thrown by “finalize()” method will
be taken care by GC thread

q There is one more way to invoke finalize() method


by:

System.runFinalization()
Runtime.getRuntime().runFinalization()
or
System.gc();
or
System.getRuntime().gc();

75

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


finalize method
v Key points to be remembered

Skeleton

@Override
protected void finalize() throws Throwable {

// do cleanup activity

Packages
v Key points to be remembered
q Java Package is a mechanism for organizing java
classes

q It is defined as a mechanism for grouping of


related types such as:
Ø Classes
Ø Interfaces
Ø Enumerations
Ø Annotions

76

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Packages
v Key points to be remembered
q Similar to the idea like storing the files under some
directories / folders

q Example
Ø Assume one is writing a java programs and not
allowed to store under some directory

Ø Instead, you are permitted to store under single


directory – it will be difficult to rename the files /
store the files

Packages
v Key points to be remembered
q Use
Ø To prevent naming conflicts
Ø To control access
Ø To make searching

q Package Examples

Package remarks
java.lang Bundles the fundamental classes
java.io Bundles the classes for input and output
functions

77

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Packages
v Key points to be remembered
q i.e., all the needed classes are arranged/defined
under some directory

q Programmer can create their own package to


bundle their own classes / interfaces under some
directory

q It is advisable to organize / group related classes


created by you

Packages
v Creating your own package
q To create own package, one must understand the
access levels / specifiers with respect to package

78

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Packages
v Creating your own package
q For the best illustration, consider an example of 2
classes.
Ø The stack class which implements the stack
(basic operations)
Ø The callStack class which will call the stack
class (only invocation)

Important class which does the basic operations of a program

Use it as a “package”

Packages
v Creating your own package
q Similar to handling a directory in the system

q To create own package

package packagename;

Directory name where the basic operation of program


exists

79

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Packages
v Constraints to execute your own package
q With reference to example, one need to create 2
programs
Ø The stack class which implements the stack
(basic operations) Ex.: Stack.java

Ø The callStack class which will call the stack


class (only invocation) Ex. CallStack.java

Packages
v Constraints to execute your own package
q With reference to example, one need to create 2
programs
Ø In “Stack.java”, first statement should be the
package statement which defines the class
belongs to which package.

package packagename;

q “No main()” will be there for an execution


q i.e., Stack.class is a package belongs to the
package “packagename”

80

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Packages
v Constraints to execute your own package
q With reference to example, one need to create 2
programs
Ø In “CallStack.java”, first statement should be
the import statement which is used to perform
instantiation.

import packagename.*;

q i.e., Stack.class is a package belongs to the


package “packagename”

Packages
v Steps to execute your own package
1. Create needed Java programs (2 or many) with the
constraints. Example: stack
2. Create 2 folders / directories in the system

Example: c:\test\my

3. Copy the class file which promotes the basic


operation to a folder that is used as “package”
Example: copy to “my” folder

81

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Packages
v Steps to execute your own package
4. Copy the class file which calls/invokes the basic
operation to a other folder
Example: copy to “test” folder

5. Execute the invocation program Ex.: execute


program in test folder

Packages
v Note
q Packages may not be visible to other folders. To
make it visible during the execution of program, it
is essential to set the path setting to the java
environment

82

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com


Packages
v Key points to be remembered

C:\test\my C:\test
package my; import my.*;
public Class Stack{
Stack(int size){ public class CallStack{
--- public static void main(String a[]){
---
} Stack s=new Stack(5);
for(int i=0;i<5;i++)
public void push(int item){ s.push(i);
--- ---
} ---
public int pop(){ for(int i=0;i<5;i++)
--- System.out.println(s.pop());
} }
} }

83

Dr.A.Thomas Paul Roy, Assistant Professor, PSNACET. Email: pauli.dgl@gmail.com

Вам также может понравиться