0% found this document useful (0 votes)
2 views78 pages

Merged

The document outlines key concepts of Object-Oriented Programming (OOP) including encapsulation, abstraction, data protection, code reusability, and polymorphism. It contrasts OOP with procedural programming, highlighting the advantages of OOP such as data security, modularity, and real-life modeling. Additionally, it discusses the importance of modeling in software development and introduces Object Modeling Technique (OMT) for system analysis and design.

Uploaded by

fakeid36788531
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views78 pages

Merged

The document outlines key concepts of Object-Oriented Programming (OOP) including encapsulation, abstraction, data protection, code reusability, and polymorphism. It contrasts OOP with procedural programming, highlighting the advantages of OOP such as data security, modularity, and real-life modeling. Additionally, it discusses the importance of modeling in software development and introduces Object Modeling Technique (OMT) for system analysis and design.

Uploaded by

fakeid36788531
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

i.

Encapsulation: Related data & procedures are clubbed together within an encapsulated structure known as class
and every entity forms a classification with data members representing the properties or attributes and the
operations on these data are treated as entity behaviour.
STUDENT
-Int roll; STUDENT
-Float marks; Roll=123;
-Char grade; Marks=70;
+Void put_data(); Char grade=’A’;
+Void show_data(); +Void put_data();
+void compute(); +Void show_data();
student s1→ +void compute();
2. Abstraction:
i. Complexity of internal representation is to be hidden form the end user.
ii. Behaviour of the new data type is similar to the basic one i.e new user defined data type treated as abstracted
data type (ADT) will work just like the traditional data type and their operations.

Complex
Int real;
Int img;
+Void addition(complex c1, complex c2);
Complex c1, c2, c3;
C3=c1+c2;

3 Data protection/hiding:

i. Attribute specific:
STUDENT
-Int roll; Private data
-Float marks;
-Char grade;
+Void put_data();
+Void show_data(); Public data
+void compute();
Student s1;
S1.roll; x
S1.put_data(); √
A
Data1;
+ operation1();
B
-Data2;
+operation2();
A cannot access any private B properties directly and it has to be via the public properties of B.
B can access both public and private properties of A.

A MODULE-1
B M
public
Private Private

C MODULE-2
D E
public
Private Private

1. Code reusability:
i. Incorporation of previously developed code/properties into another entity or module. This process reduces
redundant code development.
ii. Can selectively choose properties form the original structure to be reused in the new structure.
STUDENT
+Int roll;
+Float marks;
-Char Report;
+Void put_data();
+Void show_data();

UG_STUDENT
PG_STUDENT -int JEE score;
-int Gate_ score;
1. Monolytic Prog. Language:
i. Subroutine concept is missing
ii. Data & codes are scattered throughout the prog. (i.e no data organization)
iii. Lack of data security
iv. Not suitable for large codes or real life programming.
1. Data1
2. Data2
3. Instruction with data1 & data2 codes
4. Instruction with data1 & data2
5. Data3
6. Instruction data2 & data3
Ex: Assembly Language
2. Procedural prog. languages
The primary focus is on functions, and the overall structure follows hierarchical decomposition.
Main programme
Function-2 (with local data)

Function-1 (with local data)


Function-3 (with local data)

Serious drawback of procedural approach is that they does not model the real life prog. very well . This is because
functions are action oriented and not focused on elements.
i. Everything is procedure based i.e for every operation specific procedure or algorithm is defined.
ii. Subroutine concept is introduced
iii. Data organization is not taken care of within the procedure.
iv. Data move around openly from function to function.
v. Lack of data security as global data concept prevails.
In a multi-function prog. many vital data items are placed as global data which are always vulnerable. Also in a
large programme it is very difficult to identify what data is used by which function.
Data1 Data2 Data3
Global data
Proc1 Proc2 Proc3
3. Structured Prog. Language (Ex: C)
i. It follows procedural prog. Concept.
ii. Data organization taken care of and all the related data are clubbed in a structure. Instance of that structure
basically representing all those individual data. Also each such instance can be treated as a new user defined
data type variable.
iii. Data security issue still lacking Teacher
STUDENT Teacher Name=”AMIT DAS”;
Int roll; String name; Id=1234;
Float marks; Int id; Subject=DBMS;
Char grade; String subject;

Func1(student s1, teacher t1) Func2(student s2, teacher t2)


4. OOP Structure
It treats data as critical element and does not allows it to flow freely around the system. It ties data more closely
to the functions that operates on it and protects it form accidental modifications by the outside functions. OPP
allows decomposition of a problem into a number of entities (contains both data & Code) and the data of an entity
can only be accessed by its operations or functions. However interactions between entities are possible through
their specific interface functions. This interactions between entities or objects are basically treated as message
passing and this object to object interactions are based on specific interface functions belonging to objects.
A
Data-1 B
Function-1(public interface function) Data-2
Function-2 Function-3(public interface function)
Instance of A cannot access properties of B directly Function-4
Instance of B cannot access properties of A directly
Main Limitations of C
1. Not suitable for large scale development. The problem arises mainly due to lack of global
view i.e an abstract view (detailed internal implementation is avoided) in the modules.
int rect_area(int a, int b); int circle_area(int a); int sphere_area(int a);

float area(float a); / float area(float a, float b);


2. In case of module based programme development, modules are not totally independent.
Also data & functions are not tightly coupled.
Data-1 Data-2
Func-1() Func-3()
Func-2() Func-4()
Module-1 Module-2
3. In large prog. Development there may be common information between blocks. So, it will be
better to share (i.e reuse) those common information between blocks (instead of repeating
them again) and only provide the additional information in special cases. (this is missing in C)
student information account system
Teacher module
Object Oriented Programming Paradigm
1. Technique of visualizing the problem in a global way i.e entire programme can
be viewed together as a single unit (emphasis on tackling the common issues).
2. OOP treats data as critical elements and ties it more closely with the functions
that operate on it.
3. OOP decomposes a problem into a number of real life entity instances (also
called objects). Emphasis given on data rather than procedures.
4. Similar entities having same structure forms a classification (i.e class as the
entity template and object as its instance).
4. Objects may communicate with each other through specific interface
functions.
5. New data & functions can easily be added whenever necessary within the
entity structure.
6. Follows bottom up approach of problem solving / prog. Design.
Entity Features
1. One must have a list of entities which should be required for
problem solving
2. There are mainly two types of entities –
A. Most of the entities represent real world counterparts
B. Some of the entities are programming counterparts and the
programmer additionally requires them to solve the prog.

Entities of the system

Entities mapped form real world Entities designed for programming


(Ex: student, teacher etc.) convenience(Ex: roll call)
Advantageous Features of OOP
1. Encapsulation- Wrapping or clubbing of related data & operations/functions
into a single unit(known as class) i.e binding of related data & code within a
single structure. The data part is attribute and the code part is their behaviour.
STUDENT(class) STUDENT(object)
-Int roll; Roll=123;
-Float marks; Attributes Marks=70;
-Char grade; Char grade=’A’;
+Void put_data();
+Void show_data();
operations +Void put_data();
+Void show_data();
+void compute(); Physical existence or
+void compute();
class structure student s1 (instance of STUDENT class)
TEACHER s1.put_data(); √ (accessible)
-string name; put_data(); x (illegal statement)
- String dept;
+Void enter_data(); Teacher t1.roll; x (not accessible).
+Void print_data(); s1. name; x (not accessible)
Abstraction
1. It refers to the act of representing the essential features without including
the background details i.e complexity of internal representation is to be
hidden form the end user.
2. When objects of a class treated like a data type variable, the class is known
as abstract data type (ADT). The behaviour of this new user defined data
type is similar to the basic one in terms of declarations and operations.
3. Proper abstraction can make a complex and large problem a whole lot of
simpler and manageable.
Complex Complex c1, c2, c3;
-Int real; C3=c1+c2; (input complex object C1, C2)
-Int img; int p, q, r; (input integer data p, q)
+ complex addition(complex c1, complex c2); r=p+q;
+int addition(int a, int b);
Only those messages that the user is concerned about is passed to the object.
How the messages are responded will not be seen by the end user.
Data Protection
The prerequisite of the abstraction process is to have two different types of attributes for as
given class, one of which is to be made available to the outside world and the other part is to
be hidden form the outside world.
STUDENT
-Int roll;
Private part Student s1; S1.roll; x (not accessible & illegal code)
-Float marks;
-Char grade; S1.put_data(); √ (ok accessible)
-void compute_grade();
+Void put_data(); Public Part
+Void show_data();
A MODULE-1
B M
A public
Data1; Private Private

+ operation1();
A cannot access any private B properties directly and it
B has to be via the public properties of B. C MODULE-2
-Data2; B can access both public and private properties of A. D E
public
+operation2();
Private Private
Code Reusability
1. Inheritance/Specialization/is-a Relationship
Acquiring or sharing the common properties between two structures(classes). The common
properties are kept in the parent class while the child class derives those common properties
and adds its own specialized properties.
STUDENT
+Int roll;
+Float marks;
-Char Report;
+Void put_data();
+Void show_data();

UG_STUDENT PG_STUDENT
-int JEE score; -int Gate_ score;
2. Nested Structuring
3. Importing Modules
POLYMORPHISM
1. Ad-Hoc Polymorphism at compile time-
Functions that behave differently with different sets of arguments i.e same
function with different types or numbers of arguments. (Function overloading)
ADD FUNCTION

ADD(int a)- Called with one integer argument

ADD(int a, int b)- Called with two integer argument

ADD(string a, string b, string c)- Called with three string arguments

The complier while compiling decides the operation to be performed and


generates the object code that describes the operation. The function call
depends upon the type of arguments.
Polymorphism contd ..
2. Dynamic Polymorphism at Run-Time (Dynamic Binding/Late Binding)
 Same operation having different implementation for different types of entities i.e an
operation may exhibit different behaviours defending upon the object type it is
associated with.
Concept of procedure call to be resolved at run time rather at compile time. A
function call is associated with a polymorphic reference which dynamically refers to
the concern object type and its corresponding function is invoked.
The concern function is chosen only form the hierarchy of classes and not from
elsewhere.
STUDENT
getAttendence()

UG_STUDENT PG_STUDENT
getAttendence() getAttendence()

Student stud_ptr;
(as reference)
MESSAGE PASSING
• A set of objects communicate with each other by sending & receiving
information and it helps in modeling the real world scenario. In this case
functions of one object can access the functions of other object.
• A message is a request for the execution of a procedure call that involves
name of the object, name of the function (message), and the information to
be sent. Ex: employee.salary(Allownace)
• object message information
• Communication between objects are possible when they are alive.
EMP Allowance
-string emp_name; -int DA;
-int basic; -int HRA;
+void show_data(); +void put_allowance();
+int salary(allowance); +void get_allowance_data();
Striking Features of OOP
1. Emphasis given on data rather than procedures and maintains global view
or data abstraction.
2. Programms are divided into objects that employs real life data structure.
3. Attributes and behaviors of the object are tied together within the object
structure.
4. Data is hidden and can not be accessed by the outside world.
5. Objects may communicate with each other through specific interface
functions.
6. Previously developed data & code can be reutilized in various forms while
new data & code can be easily added whenever necessary.
7. Modular programming concept can be implemented in a better way and
hence more suitable for real life software development.
8. Software complexity can be easily managed.
1. OBJECT BASED PROGRAMMING LANGUAGE
It is the style of programming that primarily supports encapsulation and object
identity. The major features are-
(i) Encapsulation
(ii) Data hiding & accessibility mechanism
(iii) Automatic initialization and clear up of objects
(iv) operator overloading
2. Object Oriented Programming Language
It supports the features of object based language plus the additional features of
inheritance & dynamic binding.
What is Modeling
➢ A model is an abstraction for the purpose of understanding the system before building it.
➢ A model hides the non-essential characteristics of a system and highlights those which are
pertinent for understanding.
➢ A model provides a means for conceptualization and communication of ideas in a precise
and unambiguous form.
➢ Modelling enables us to cope with the complexity of the system
➢ Modelling is used frequently, during many of the phases of the software life cycle such as
analysis, design and implementation.

Abstract view of TV remote & call handling procedure for a mobile phone
Why do we model?
➢To evaluate the outcome of a physical entity before actually building it.
➢ To set the stage for communication between customers and developers.
➢ For visualization i.e. for finding alternative representations.
➢ For reduction of complexity in order to understand it.
OBJECT MODELING TECHNIQUE (OMT)
➢ This concept introduces a methodology for analysis, design and implementation
of a system with object-oriented software development techniques/process.
➢It is a fast, intuitive approach for identifying and modelling all the objects of a
system.
➢It focuses three different viewpoints i.e. the static, dynamic and functional
behaviours of the system.
➢These are described by object model, dynamic model and functional model of
the OMT.
Different Viewpoints of OMT
1. Object Model- It describes the static, structural and data aspects of a system in terms of
objects and their relationships.
2. Dynamic model-It describes the temporal, behavioural and control aspects of the system. It
actually focuses on state changes for the various objects with respect to the event.
3. Functional model- It focuses on process perspective of the system and mainly defines the
critical functional parts with the help of Data Flow Diagrams (DFDs).

Dynamic Model Functional Model


Object Model
➢It describes the structure of the objects, their identity, and their relationships
with other objects.
➢It depicts the primary view and overall decomposition of the system.
➢It provides the framework into which other models are placed.
➢It is represented graphically with an object diagram.
Class
➢A class is a template or logical structure where certain basic characteristics of a
set of objects are defined in terms of attributes and operations.
➢ Objects are physical instances created from the class. Book
Class Name title: string
Attribute-name1:data-type1=default-val1 author: string
Attribute-name2:data-type2=default-val2 publisher: string
open() :int
Operation-name1(arguments1):result-type1 close() :int
Operation-name2(arguments2):result-type2 read() :void
Objects
Object is an abstraction or thing with crisp boundaries and meaning for the
problem. Alternatively an object is an instance of a class with the following features.
1. Unique identification- Every object has a unique name by which it is identified.
2. Set of attributes- Every object has a set of properties in which we are interested.
3. Set of states- Values of attributes of an object constitute the state of the object.
Every object will have a number of states but at a given time it can be in one state.
4. Set of operations (behaviour) - Externally visible actions an object can perform.
When an operation is performed, the state of the object may change.
(Class Name)
Object name → general structure of object instance for the book class in OMT

(Book) (Book) → Examples of objects of Book Class


Physics Mathematics
LINK & ASSOCIATION
1. A link is a physical or conceptual connection between object instances. In OMT, link is
represented by a line labelled with its name between object instances.
(STUDENT) Enrolled in (COLLEGE)
AMIT GCECT
2. An association describes a group of links with common structure and common
semantics between two or more classes. Association is represented by a line labelled
with the association name written in an italic manner between classes.
Class Name-1 Class Name-2
Association Name
Association names are optional. In case of a binary association, the name reads in a
particular direction (i.e. left to right), but the binary association can be traversed in either
directions i.e associations are bi-directional in nature.
Multiplicity: It specifies how many instances of one class may relate to a single instance
of an associated class. Multiplicity constrain basically indicates the number of related
objects between classes.
Multiplicity Indicator
STUDENT Enrolled in DEPARTMENT ➢ Line without any ball
(0,….1) indicates one-to-one
DEPARTMENT association.
STUDENT Enrolled in
➢ Hollow ball indicates zero or
(0,1,….,N) one.
STUDENT Enrolled in DEPARTMENT ➢ Solid ball indicates zero, one
(1,2,6) or more.
STUDENT Enrolled in DEPARTMENT
➢ Numbers written on solid
ball such as 1,2,6 indicates 1
(1+)
or 2 or 6.
STUDENT Enrolled in DEPARTMENT ➢ Numbers written on solid
ball such as 1+ indicates 1
SALESMAN Works for in COMPANY or more.
Association Types based on Multiplicity
• An association can be unary, binary, ternary or n-ary
teaches
PERSON

Unary association between same classes (reflexive association)


Ternary association is an association among three classes. On the same line, n-ary
association is an association among n classes and is denoted with diamond box.
PROGRAMMER works for PROJECT

LANGUAGE
LINK ATTRIBUTES
Some times, an attribute(s) cannot be associated with either of the two classes.
In such cases, the attribute(s) is associated with the association and is called as
link attribute. It is the property of the link and not any of the individual class.
SALESMAN Works for COMPANY

SALARY
Date-of-Join

It is also possible to model link attributes as a class and such class is called as link
class. Each link becomes one instance of the class. The notation for this kind of an
association is the same as for a link attribute. FILE Accessibly by USER

Authorization
Access-permission
ROLE NAMES
➢A role is one end of an association.
➢A binary association can have two roles, each of which may have a role name.
➢A role name is a name uniquely identifies one end of an association.
➢Role provides a way of viewing a binary association as a traversal from one
object to a set of associated objects.
employee employer
SALESMAN COMPANY
Works for
➢Role names are necessary for associations between two objects of the same class.
➢They are also useful to distinguish between two associations between the same pair of classes
➢All role names on the far end of associations attached to a class must be unique.
Ordering
Usually the objects on the "many" side of an association have no explicit order,
and can be regarded as a set. Writing {ordered} next to the multiplicity dot
indicates an ordered set of objects of an association.
WINDOW {ordered} SCREEN
visible on
Qualification
➢A qualifier is a special association attribute that reduces the effective multiplicity
of an association.
➢One-to-many and many-to-many associations may be qualified.
➢The advantage of qualification is that it improves the semantic accuracy and also
increases the visibility of navigation paths.
BANK ACOUNT NUMBER PERSON
Aggregation
➢Aggregation is another form of relationship between classes. It is a tightly
coupled form of association with some extra semantics.
➢It is “part-whole” or “a-part-of” relationship in which one object is part of other.
TEAM maintains PLAYER
Aggregation can be fixed, variable or recursive.
➢In a fixed aggregation number and subtypes are fixed i.e. predefined.
➢In variable aggregation number of parts may vary but number of levels is finite.
DOCUMENT PARAGRAPH SENTENCE WORD
➢ A recursive aggregate contains, directly or indirectly, an instance of the same
aggregate. The number of levels is unlimited here.
PROGRAMME BLOCK

COMPOUND STATEMENT SIMPLE STATEMENT


Differences between Conventional Programming & OOP
Conventional Programming OOP
Divides the whole programme into several functions Divides the whole programme into number of entities
i.e emphasis on procedures. called objects i.e emphasis on objects
Not suitable for real world scenario Perfectly suitable for real world software development.
Follows top-down approach of progamme Follows bottom-up approach of programme
development development
Does not support code reusability with security Supports code reusability with strong security features.
feature.
Mostly suitable for medium sized applications Perfectly suitable for large & complex systems.
Adding new data & code is not easier for the iterative Adding new data & code is relatively easier for the
software development i.e modification is difficult. iterative software development due to secure
interfacing between modules and objects.
There is no data access restriction with the use of Access of data & code can be effectively restricted with
access specifiers. the use of access specifiers.
Data & code is not secured Data & code is secured
Data & procedure specific abstraction not supported Supports data and procedural abstraction
Ex:- C Ex: C++, java etc.
Major & Minor Elements in OOP
Major Elements- Abstraction, Encapsulation, Modularity and Hierarchy. A model
without any one of these elements is not object-oriented.
ABSTRACTION-
➢Abstraction is to simplify a problem by omitting unnecessary / irrelevant
details and this is also called Model building.
➢Several abstractions of the same problem are possible i.e use different models
for different aspects of the system.
➢For complex problems hierarchy of abstractions may be considered.
Encapsulation-
➢It compartmentalizes the elements of an abstraction with structural attributes
and behaviors.
➢Putting everything into one envelop and provide others to use it through a
well planned interface.
Abstraction Encapsulation
Solves the problem in the design level Solves the problem in the implementation level
Provides outer layout used in terms of design Provides inner layout, used in terms of Outer.

MODULARITY-
➢ Partitioning a programme into individual components for managing the complexity.
➢ Modules compile separately or together.
➢ They are Connected with other modules.
ADVANTAGES-
➢ Decomposition of the problem into individual components.
➢ Enable reuse of existing components.
➢ Understanding module as a unit and hence easy to change.
➢ Errors are localized and local modification is possible.
Main Focus Points of Modularity
➢ Group logically related abstraction
➢ Minimize dependency among modules
➢ Simple enough to understand fully.
Hierarchy – It is a ranking or ordering of abstractions and mainly used to share the common
functionalities between objects or entities. It is of two types
A. IS–A hierarchy B. PART–OF hierarchy
Minor Elements- Each one of these following elements are useful but not essential.
1. Typing 2.Concurrency and 3. Persistence
1.Typing- A typing is the enforcement of the class to an object, such that objects of different
types- (i) may not be interchanged or at the most (ii) they are interchanged only in very
restricted ways.
2. Concurrency- It is the property that distinguishes an active object form the inactive one. It
allows multiple task to execute, interact and collaborate at the same time.
3. Persistence- It is the property of an object through which its existence transcends time. It
decides the fate of objects over time and space.
Time- Object continues to exist after its creator destroys it.
Space- Object’s location moves form the address space in which it was created.
Class to class relationships
EMP Project
-string emp_name; -int proj_number;
-int basic; -string p_name;
-int p_id; -string p_duration;
+void show_data(); -int p_budget;
+int salary(allowance); +void put_data(emp e);
+void get_data();

Project
EMP -int proj_number;
-string emp_name; -string p_name;
-int basic; -string p_duration;
+void show_data(); -int p_budget;
+int salary(allowance); EMP e[];
+void put_data();
+void get_data();
STRING HANDLING METHODS
Java string class container package – java.lang.String
The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as
instances of this class.
String str = "abc"; is equivalent to:
char data[] = {'a', 'b', 'c'};
String str1 = new String(data);
String str2=new String(“abc”);
class string_concat
{
public static void main(String args[]){
String str="HELLO";
char data[]={'H','E','L','L','O'};
String s=new String(data);
System.out.println(str);
System.out.println(data);
System.out.println(s);
System.out.println(str+" AND "+s);
}
}
SUBSTRING CUTTING FROM THE MOTHER STRING
1. String substring (int began, int end) -> cuts a substring form the method invocation string
with starting index at began and the ending index at end-1.
2. String substring (int began) -> cuts the substring form the method invocation string with
starting index at began and upto the last index of the string.
Example-
class remove_char
{
static String remove_charAt(String str, int pos){
return str.substring(0, pos)+str.substring(pos+1);
}
public static void main(String args[])
{ String str="GOOD IS JAVA";
System.out.println(remove_charAt(str,2));
}
}
COMMAND LINE ARGUMENTS
class command_line_argument
{
public static void main(String args[]){
for (int i=0; i<args.length;i++)
System.out.print(args[i]+" ");
System.out.println();
System.out.println("LENGTH OF THE FIRST ARGUMENT:-"+args[0].length());
//int length()-> returns the length of the invoked string object
System.out.println("EQUALITY OF THE FIRST TWO ARGUMENTS:-
"+args[0].equals(args[1]));
// boolean equals(String str) -> compares invoked string with the passed argument string
System.out.println("CHARACTER AT INDEX POSITION 2 FOR THE FIRST ARGUMENTS:-
"+args[0].charAt(2));
//char charAt(int index) -> returns the character at the specified index position
}
}
KEYBOARD INPUT
import java.io.*;
class input{
public static void main(String args[]) throws IOException
{
int a=0; String str=" "; int b=0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("\n");
System.out.print("ENTER YOUR NAME:-");
str=br.readLine();
System.out.println("\n");
System.out.println("YOUR NAME:-"+str);
System.out.println("\n");
System.out.print("ENTER A NUMBER:-");
a=Integer.parseInt(br.readLine());
System.out.println("\n");
System.out.println("YOUR ENTERED NUMBER:-"+a);
}
}
LEXIOGRAPHICAL COMPARISON WITH EXAMPLE
import java.io.*;
class string_compare
{ public static void main(String args[])throws IOException
{ String s1=""; String s2="";
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("ENTER FIRST STRING:-"); s1=br.readLine();
System.out.print("ENTER SECOND STRING:-"); s2=br.readLine();
int a=s1.compareTo(s2);
if(a==0) System.out.println("THE TWO STRINGS ARE EQUAL");
else if(a<0) System.out.println("FIRST STRING IS SMALLER");
else System.out.println("FIRST STRING IS LARGER");
System.out.println("THE VALUE OF A:-"+a);
}
}
SUB STRING PATTERN SEARCHING WITH CONTAINS METHOD
• The contains() method checks whether the specified substring (i.e sequence of
characters) is present in the mother string or not.
• Syntax of contains()
• string.contains(String str) and the return type is boolean (i.e true/false)
class string_contain
{
public static void main(String[] args) {
String str = "GCECT IS A GOOD COLLEGE";
System.out.println(str.contains("GCECT"));
System.out.println(str.contains("GOOD"));
System.out.println(str.contains("KGEC"));
}
}
STRING OBJECT CREATION CONCEPT
• There are two ways to create a String object:
• By string literal : using double quotes. For Example: String s=“Welcome”;
• By new keyword : Java String is created by using a keyword “new”.
• For example: String s=new String(“Welcome”);
• Java String Pool: refers to collection of Strings which are stored in heap memory.
whenever a new object is created, String pool first checks whether the object is
already present in the pool or not. If it is present, then same reference is
returned to the variable else new object will be created in the String pool.
Reversing a String by Reading It In a Reverse Manner
class reverse_first
{
public static void main(String args[]){
String s1="";
for (int i=args[0].length()-1; i>=0;i--)
s1=s1+args[0].charAt(i);
System.out.println(s1);
System.out.println("First String Palindrome:-"+args[0].equals(s1));
}
}
Java Architecture

1
Agenda

Evolution of Java

Java Architecture

2
Evolution of Java

3
Key Founders
 Java was the brainchild of:
• James Gosling

• Patrick Naughton

• Mike Sheridan

 The origin of Java can be traced back to the fall of 1991, and was
initially called Greentalk later renamed to Oak.
 Oak was renamed as Java in 1995

4
Design Goal
 Java was originally meant to be a platform-neutral language for
embedded software in devices.

 The goal was to move away from platform and OS-specific compilers
that would compile source for a particular target platform to a language
that would be portable, and platform-independent.

 The language could be used to produce platform-neutral code.

5
Java Architecture

6
Java Architecture
Compile-time Run-time Environment
step3
Environment step1
Class Java
Class
Java
Source Loader Libraries
(.java)
Bytecode
Verifier step4

step2 Java
Bytecodes
Java Compiler move locally Java
Just in
Time
step5
or through Interpreter
Compiler Java
network
Virtual
machine

Runtime System
Java
Bytecode
(.class ) Operating System

Hardware

7
Java Architecture (Contd.).
Step1:
Create a java source code with .java extension

Step2:
Compile the source code using java compiler, which will create bytecode file with .class
extension

Step3:
Class loader reads both the user defined and library classes into the memory for execution

8
Java Architecture (Contd.).
Step4:
Bytecode verifier validates all the bytecodes are valid and do not violate Java’s security
restrictions

Step5:
JVM reads bytecodes and translates into machine code for execution. While execution of the
program the code will interact to the operating system and hardware

9
The 5 phases of Java Programs
Java programs can typically be developed in five stages:
1. Edit
Use an editor to type Java program (Welcome.java)
2. Compile
• Use a compiler to translate Java program into an intermediate language called
bytecodes, understood by Java interpreter (javac Welcome.java)

• Use a compiler to create .class file, containing bytecodes (Welcome.class)


3. Loading
Use a class loader to read bytecodes from .class file into memory

10
The 5 phases of Java Programs (Contd.).
4. Verify
Use a Bytecode verifier to make sure bytecodes are valid and do not violate security
restrictions
5. Execute
• Java Virtual Machine (JVM) uses a combination of interpretation and just-in-time
compilation to translate bytecodes into machine language

• Applications are run on user's machine, i.e. executed by interpreter with java command
(java Welcome)

11
Java Virtual Machine

• The output of the compiler is bytecode


• The bytecodes are executed by JVM
• It is an interpreter which converts the
byte code to machine specific
instructions
and executes
• JVM is platform specific

12
The Java Architecture – The JVM (Contd.).
 Most modern languages are designed to be compiled

 Compilation is a one-time exercise and executes faster

 Execution of compiled code over the Internet an impossibility

 Executable code always generated to a CPU-OS combination

 Interpreting a Java program into byte code facilitates its execution in a wide variety of
environments

13
The Java Architecture – The JVM (Contd.).
 Only the Java Virtual Machine (JVM) needs to be implemented for each platform

 Once the Java runtime package exists for a given system, any Java program can run on it

 The JVM will differ from platform to platform, and is, platform-specific

 All versions of JVM interprets the Java byte codes.

14
The Java Architecture – The JVM (Contd.).
 Interpreted code runs much slower compared to executable code

 The use of bytecode enables the Java runtime system to execute programs much faster

 Java facilitates on-the-fly compilation of bytecode into native code

15
The Java Architecture – The Adaptive optimizer
 Another type of execution engine is an adaptive optimizer

 The virtual machine starts by interpreting bytecodes

 It also keeps a tab on the code that is running and identifies only the heavily used areas

 The JVM compiles these heavily used areas of code into native code

 The rest of the code, which is not heavily used continues to be interpreted and executed

16
The Java Architecture - The Class Loader
 The class loader is that part of the VM that is important from:
 A security standpoint
 Network mobility

 The class loader loads a compiled Java source file (.class files represented as bytecode) into
the Java Virtual Machine (JVM)

 The bootstrap class loader is responsible for loading the classes, programmer defined classes
as well as Java's API classes

17
The Java Architecture - The Java .class file
 The Java class file is designed for
 platform independence
 network mobility

 The class file is compiled to a target JVM, but independent of underlying host platforms

 The Java class file is a binary file that has the capability to run on any platform

18
Quiz
1. Write the correct order of the Java program execution.
A. Class Loader
B. Interpretation
C. Compilation
D. Byte Code Verification
E. Java Source Code
F. Execution

2. Which of the following is used to load a .class file?


A. Class Loader
B. Byte Code Verifier
C. JIT Compiler
D. Interpreter
19
Quiz(Contd.).
3. When a java program is compiled, it creates a
A. an obj file
B. an exe file
C. a .class file
D. a .sh file

4. The JDK is a superset of the JRE, and contains everything that is in the JRE, plus
tools such as the compilers and debuggers necessary for developing applets and
applications.
A. TRUE
B. FALSE

20
Summary

In this session, you were able to :

 Learn about Evolution of Java and forces that shaped it.


 Understand Java Architecture along with JVM concepts.

21
Thank You

22
CODE REUABILITY WITH INHERITANCE
Class A
Int x;
A(int i){} A(){}
Void show(){}

Class B Class B
Int x;
Int y; Int y;
B(int I, int j){} B(){} B(int I, int j){} B(){}
Void display(){} Void show(){}
Void display(){}

➢ Whenever child object is created, at first the parent data members are initialized either
explicitly or implicitly. It means immediate parent class constructor is called first inside the
child class constructor.
➢ Private members & constructors of the parent class never inherited.
Types of Inheritance

Not possible through classes, but


can be indirectly possible through
interfaces
Method Overriding
• Same method name and prototype for both child and parent class.
• Both parent & child class overridden method having same return type.
class A{
void show(){ System.out.println("INSIDE A SHOW"); }
void F1(){System.out.println("INSIDE A F11");}
}
class B extends A{
void show(){ System.out.println("INSIDE B SHOW"); }
void display() { System.out.println("INSIDE B DISPLAY"); }
void show(int x) {System.out.println("X:-"+x);}
}
class over_ride{
public static void main(String args[]){
B b1=new B();
b1.show(); // calls B show()
A a1=new A();
a1.show(); // calls A show()
a1.show(5); // compiler error
}
}
ASSINGMENT-5
Class A{ private int x; A(int i){} void show() { print x of A} void f1(){}}
Class B extends A{private int x; B(int i, int j){} void show() { print x of B} void f2(){}}
Class C extends B {private int x=9; C(int I, int j, int k){} void show() { print x of C} void
f3(){}}
Class demo{ public static void main(String args[]){
1. Initialize child and parent data members with constructor
2. Print all x and call f1(), f2(), f3() with only one object of class C}
3. Apply polymorphism such that class A objects points to class C object and using this
idea call all the show methods of A, B and C
}
Dynamic Resolving of Method Calls (Late Binding/Ploymorphism)
1. Parent class or superclass object or object reference variable refers to the subclass
object, but the reverse is not true.
Class A{
1. void show(){} // class A version
2. void show(int b){}
}
Class B extends A{
3. void show(){} // class B version
4. void display(){}
}
class demo{ B b1=new B(); b1.show(); //A a1=new A(); A a1=b1; a1.show();}
2.Whenever a method is called using property 1, then the compiler first looks whether that
called method belongs to the parent class or not. If it belongs to the parent class then go to
step 3, otherwise compilation error.
3. If step 2 is Ok, then JVM looks what object this parent class object/reference is pointing
and calls that class version of the method
WAY OF PREVENTING INHERITANCE
ABSTRACT CLASS
➢A class that contains one or more abstract methods has to be declared as abstract.
➢There can be no objects of an abstract class i.e an abstract class cannot be directly instantiated with
the new operator.
➢Abstract constructors or abstract static methods can not be declared. Any subclass of an abstract
class must either implement all of the abstract methods declared in the superclass, or be itself
declared as abstract
abstract class A{ int x; A(int i){x=i;} abstract void show(); void display() { System.out.println("INSIDE
A DISPLAY"); } }
abstract class C{}
class B extends A{
int y;
B(int i, int j){super(i); y=j;} void show(){ System.out.println("X:-"+x); System.out.println("Y:-"+y); }
void display() { System.out.println("INSIDE B DISPLAY"); }
}
class abstract_method{
public static void main(String args[]){ B b1=new B(7,9); A a1=b1; a1.show(); a1.display();
}
}
Interface Implementation
➢Interface is full abstraction form of the class (but not a class). It contains only abstract methods and
its variables are implicitly final and static.
➢Interface members are declared either public or with default access specifiers
➢A class can implement multiple interfaces, but can not extend multiple abstract classes. While
implementing an interface, a class must override all the abstract methods of the interface (using
public access specifier in the implementing class), otherwise that class must be declared as
abstract.
➢Interface implementation follows the same dynamic method resolving rules that are applied for
classes.
interface A{ int x=5; void f1();} interface B{int y=7; void f2();}
class C implements A,B{ public void f1(){} public void f2(){} pubic void f3(){} }
Class demo{
Public static void main(String args[]){
C c1=new C();
A a1=c1; a1.f1();
B b1=c1; b1.f2();
C1.f3();
}}
Interfaces Can be Extended
interface A{ void f1();} interface C{void f3();}
interface B extends A,C {void f2();}
abstract class E{ abstract void f4(); }
interface F{ void f5();}
class D extends E implements B, F{
public void f1(){}
public void f2(){}
public void f3(){}
public void f4(){}
public void f5(){}
}
EXCEPTION HANDLING
➢ An exception is an abnormal condition that arises in a code sequence at run
time, i.e an exception is a run-time error situation
➢ Java exception is an object that describes an exceptional (i.e error) condition
that has occurred in a piece of code and thrown in the method that caused
the error.
➢ That method may choose to handle the exception itself, or pass it on. Either
way, at some point, the exception is caught and processed.
➢ Example:
class Exc0 {
public static void main(String args[]) {
int d = 0;
int a = 42 / d; } } // arithmetic exception object will be thrown
Output→java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)
Exception Handling contd..
➢An exception (or exceptional event) arises during the execution of a program.
➢When an Exception occurs, the program/Application terminates abnormally,
which is not recommended, therefore, these exceptions are to be handled.
➢Checked exceptions − A checked exception is an exception that is
checked (notified) by the compiler at compilation-time, these are also
called as compile time exceptions.
➢Unchecked exceptions − It occurs at the time of execution and also
called as Runtime Exceptions. These Runtime exceptions are
ignored at the time of compilation and are handled during run time.
➢Errors − These are not exceptions at all and are beyond the control of
the programmer. For example, if a stack overflow occurs, an error will
arise. They are also ignored at the time of compilation and cannot
usually be handled by the program.
Exception Class Hierarchy
All exception classes are subtypes of the java.lang.Exception class.
The exception class is a subclass of the Throwable class. Other than the
exception class there is another subclass called Error which is derived from the
Throwable class.
Errors are abnormal conditions that happen in case of severe failures, these are
not handled by the Java programs. Normally, programs cannot recover from
errors.
Use of throw clause
➢Program can throw an exception explicitly form the method body, using the throw statement.
➢Any subsequent statements after the throw statement; are not executed.
➢The nearest catch block is inspected to match the type of exception. If no match found, then
the default exception handler halts the program and prints the stack trace.
class ThrowDemo {
static void demoproc() {
try {
NullPointerException e= new NullPointerException("demo");
throw e;
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}}}
Use of throws clause
➢If a method throws an exception that it does not handle, then it must specify
this at the method prototype, so that caller of the method can take guard.
➢This is done by including a throws clause in the method’s prototype.
➢The ‘throws’ clause is not applicable for Error/RuntimeException or any of their
subclasses i.e we can not declare such exception types using the ‘thows’ clause.
➢This ‘throws’ clause is capable of declaring multiple exceptions at the function
prototype, although one exception will be thrown at a single instance of time.
➢If a method explicitly throws an exception but does not handles that exception
within the method body or declares it at the method prototype, then a
compilation error should result.
Use of ‘thows’ Clause--- a Simple Demo
class ThrowsDemo {
static void throwOne() throws IllegalAccessException, NullpointerException, Exception
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
USE OF FINALLY BLOCK
➢When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear
path that alters the normal flow through the method
➢finally creates a block of code that will be executed after a try/catch block and before
the code following the try/catch block.
➢The finally block will be executed whether or not an exception is thrown. If an
exception is thrown, the finally block will execute even if no catch statement
matches the exception. Any time a method is about to return to the caller from
inside a try/catch block, via an uncaught exception or an explicit return statement,
the finally clause is also executed just before the method returns. This can be
useful for shutting down and releasing resources.
➢The finally clause is optional. However, each try statement requires at least one catch
or a finally clause.
Sequence of finally declaration ---- try{}
catch() {}
finally{} /////

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