Professional Documents
Culture Documents
Oops Notes
Oops Notes
There are some other differences which can be explained with the help of a comparison chart.
Comparison Chart
COMPARISON
the task done" i.e. on the objects are permitted to access the entities of
program .
Entity accessing mode No access specifier Access specifier are "public", "private",
observed. "protected".
Data hiding & security There is no proper way of Data is hidden in three modes public,
hiding the data, so data is private, and protected. hence data security
insecure increases.
Data sharing Global data is shared among Data is shared among the objects through the
. inheritance.
OOP’s chief concern is to hide the data from non-member functions of a class, which it treats like
“critical information”. Data is closely tied to the member functions of a class, which operates on
it. It doesn’t allow any non-member function to modify the data inside it. Objects interact with
each other through member functions to access their data.
OOP is developed on the basic concept of “object”, “classes”, “data encapsulation or abstraction”,”
inheritance”, and “Polymorphism/overloading”. In OOP, programs can be divided into modules
by partitioning data and functions, which further can be used as templates for creating new copies
of modules, if required. Therefore, it is an approach that facilitates in modularizing programs by
constructing a partitioned memory area for data and functions.Object-Oriented Concepts
POP is a conventional way of programming. Procedural programming is where the primary focus
is on getting the task done in sequential order. Flowchart organizes the flow of control of the
program. If the program is extensive, it is structured in some small units called functions, which
shares global data. Here, the concern of data security arises, as there is an unintentional change in
the program by functions.
POP characteristics
While designing a program, POP follows a top-down programming approach.
Majority of the functions allows global data to be shared.
It also divides larger programs into smaller parts called as functions.
It allows a free data movement around the system from functions to functions.
Data is transformed by the functions from one form to another.
It gives importance to the concept of the functions.
Advantages
Disadvantages
Conclusion
The flaws of POP arises the need for OOP. OOP corrects the flaws of POP by introducing the
concept of “object” and “classes”. It enhances the data security and automatic initialization &
clear-up of objects. OOP makes it possible to create multiple instances of the object without any
interference.
Section- B
Object-oriented Methodology:
The object modeling techniques is an methodology of object oriented analysis,
design and implementation that focuses on creating a model of objects from the real
world and then to use this model to develop object–oriented software. object
modeling technique, OMT was developed by James Rambaugh. Now-a-days,
OMT is one of the most popular object oriented development techniques. It is
primarily used by system and software developers to support full life cycle
development while targeting object oriented implementations. The OMT methodology
covers the full software development life cycle.
Benefits of Object Oriented Methodologies
3. It provides nice structures for thinking, abstracting and leads to modular design.
4. Simplicity:
The software object's model complexity is reduced and the program structure is very clear.
5. Reusability:
It is a desired goal of all development process.
It contains both data and functions which act on data.
It makes easy to reuse the code in a new system.
Messages provide a predefined interface to an object's data and functionality.
6. Increased Quality:
This feature increases in quality is largely a by-product of this program reuse.
7. Maintainable:
The OOP method makes code more maintainable.
The objects can be maintained separately, making locating and fixing problems easier.
8. Scalable:
The object oriented applications are more scalable than structured approach.
It makes easy to replace the old and aging code with faster algorithms and newer technology.
9. Modularity:
The OOD systems are easier to modify.
It can be altered in fundamental ways without ever breaking up since changes are neatly
encapsulated.
10. Modifiability:
It is easy to make minor changes in the data representation or the procedures in an object
oriented program.
11. Client/Server Architecture:
It involves the transmission of messages back and forth over a network.
1-Object Modelling
Object modelling develops the static structure of the software system in terms of objects.
It identifies the objects, the classes into which the objects can be grouped into and the
relationships between the objects. It also identifies the main attributes and operations that
characterize each class.
The process of object modelling can be visualized in the following steps −
2-Dynamic Modelling
After the static behavior of the system is analyzed, its behavior with respect to time and
external changes needs to be examined. This is the purpose of dynamic modelling.
Dynamic Modelling can be defined as “a way of describing how an individual object
responds to events, either internal events triggered by other objects, or external events
triggered by the outside world”.
The process of dynamic modelling can be visualized in the following steps −
3-Functional Modelling
Functional Modelling is the final component of object-oriented analysis. The functional
model shows the processes that are performed within an object and how the data changes
as it moves between methods. It specifies the meaning of the operations of object
modelling and the actions of dynamic modelling. The functional model corresponds to the
data flow diagram of traditional structured analysis.
The process of functional modelling can be visualized in the following steps −
Advantages Disadvantages
Focuses on data rather than the procedures as in Functionality is restricted within objects. This may
Structured Analysis. pose a problem for systems which are intrinsically
procedural or computational in nature.
The principles of encapsulation and data hiding It cannot identify which objects would generate an
help the developer to develop systems that cannot optimal system design.
be tampered by other parts of the system.
The principles of encapsulation and data hiding The object-oriented models do not easily show the
help the developer to develop systems that cannot communications between the objects in the system.
be tampered by other parts of the system.
It allows effective management of software All the interfaces between the objects cannot be
complexity by the virtue of modularity. represented in a single diagram.
Problem Statement: The first step in the research process is to choose a problem
to investigate. The researcher begins with a general topic and then narrows it to a specific
problem statement, which is a detailed description of the problem and its importance.
A problem statement describes the research problem and identifies potential causes or
solutions. A problem statement also conveys the reason the problem is important and who
is affected by the problem.
Types:There are two general types of problem statements: quantitative and qualitative.
The problem statement in a quantitative research study names the variables and population
to be studied, and asks a question about the relationship between the variables. A
qualitative study, on the other hand, also begins with a problem statement, but it is stated
much more broadly than in a quantitative study. In other words, it states the general purpose
of the study, but the focus may change as the study progresses.
Characteristics
Systems analysis
Systems design
Systems Analysis
It is a process of collecting and interpreting facts, identifying the problems, and decomposition
of a system into its components.
System analysis is conducted for the purpose of studying a system or its parts in order to identify
its objectives. It is a problem solving technique that improves the system and ensures that all the
components of the system work efficiently to accomplish their purpose.
Analysis specifies what the system should do.
Systems Design
It is a process of planning a new business system or replacing an existing system by defining its
components or modules to satisfy the specific requirements. Before planning, you need to
understand the old system thoroughly and determine how computers can best be used in order to
operate efficiently.
System Design focuses on how to accomplish the objective of the system.
System Analysis and Design (SAD) mainly focuses on −
Systems
Processes
Technology
What is a System?
The word System is derived from Greek word System, which means an organized relationship
between any set of components to achieve some common cause or objective.
Constraints of a System
A system must have three basic constraints −
A system must have some structure and behavior which is designed to achieve a
predefined objective.
Interconnectivity and interdependence must exist among the system
components.
The objectives of the organization have a higher priority than the objectives of
its subsystems.
For example, traffic management system, payroll system, automatic library system,
human resources information system.
Properties of a System
A system has the following properties −
Organization
Organization implies structure and order. It is the arrangement of components that
helps to achieve predetermined objectives.
Interaction
It is defined by the manner in which the components operate with each other.
For example, in an organization, purchasing department must interact with
production department and payroll with personnel department.
Interdependence
Interdependence means how the components of a system depend on one another.
For proper functioning, the components are coordinated and linked together
according to a specified plan. The output of one subsystem is the required by other
subsystem as input.
Integration
Integration is concerned with how a system components are connected together. It
means that the parts of the system work together within the system even if each part
performs a unique function.
Central Objective
The objective of system must be central. It may be real or stated. It is not uncommon
for an organization to state an objective and operate to achieve another.
The users must know the main objective of a computer application early in the
analysis for a successful design and conversion.
Elements of a System
The following diagram shows the elements of a system −
Processor(s)
The processor is the element of a system that involves the actual transformation of input into
output.
It is the operational component of a system. Processors may modify the input either totally or
partially, depending on the output specification.
As the output specifications change, so does the processing. In some cases, input is also modified
to enable the processor for handling the transformation.
Control
The control element guides the system.
It is the decision–making subsystem that controls the pattern of activities governing input,
processing, and output.
The behavior of a computer System is controlled by the Operating System and software. In order
to keep system in balance, what and how much input is needed is determined by Output
Specifications.
Feedback
Feedback provides the control in a dynamic system.
Positive feedback is routine in nature that encourages the performance of the system.
Negative feedback is informational in nature that provides the controller with information for
action.
Environment
The environment is the “supersystem” within which an organization operates.
It is the source of external elements that strike on the system.
It determines how a system must function. For example, vendors and competitors of organization’s
environment, may provide constraints that affect the actual performance of the business.
Types of Systems
The systems can be divided into the following types −
Physical or Abstract Systems
Physical systems are tangible entities. We can touch and feel them.
Physical System may be static or dynamic in nature. For example, desks and chairs are the physical
parts of computer center which are static. A programmed computer is a dynamic system in which
programs, data, and applications can change according to the user's needs.
Abstract systems are non-physical entities or conceptual that may be formulas, representation or
model of a real system.
Systems Models
Schematic Models
A schematic model is a 2-D chart that shows system elements and their linkages.
Different arrows are used to show information flow, material flow, and information feedback.
Categories of Information
There are three categories of information related to managerial levels and the
decision managers make.
Strategic Information
This information is required by topmost management for long range planning policies for next few
years. For example, trends in revenues, financial investment, and human resources, and population
growth.
This type of information is achieved with the aid of Decision Support System (DSS).
Managerial Information
This type of Information is required by middle management for short and intermediate range
planning which is in terms of months. For example, sales analysis, cash flow projection, and
annual financial statements.
It is achieved with the aid of Management Information Systems (MIS).
Operational information
This type of information is required by low management for daily and short term planning to
enforce day-to-day operational activities. For example, keeping employee attendance records,
overdue purchase orders, and current stocks available.
It is achieved with the aid of Data Processing Systems (DPS).
Phase of OMT
The OMT methodology covers the full software development life cycle. The methodology has
the following phase.
1. Analysis - Analysis is the first phase of OMT methodology. The aim of analysis
phase is to build a model of the real world situation to show its important properties
and domain. This phase is concerned with preparation of precise and correct
modelling of the real world. The analysis phase starts with defining a problem
statement which includes a set of goals. This problem statement is then expanded
into three models; an object model, a dynamic model and a functional model. The
object model shows the static data structure or skeleton of the real world system
and divides the whole application into objects.
2. System design - The system design phase comes after the analysis phase. System
design phase determines the overall system architecture using subsystems,
concurrent tasks and data storage. During system design, the high level structure
of the system is designed. The decisions made during system design are:
o The system is organized in to sub-systems which are then allocated to
processes and tasks, taking into account concurrency and collaboration.
o Persistent data storage is established along with a strategy to manage shared
or global information.
o Boundary situations are checked to help guide trade off priorities.
3. Object design - The object design phase comes after the system design phase is
over. Here the implementation plan is developed. Object design is concerned with
fully classifying the existing and remaining classes, associations, attributes and
operations necessary for implementing a solution to the problem. In object design:
o Operations and data structures are fully defined along with any internal
objects needed for implementation.
o Class level associations are determined.
o Issues of inheritance, aggregation, association and default values are
checked.
4. Implementation - Implementation pahse of the OMT is a matter of translating the
design in to a programming language constructs. It is important to have good
software engineering practice so that the design phase is smoothly translated in to
the implementation phase. Thus while selecting programming language all
constructs should be kept in mind for following noteworthy points.
o To increase flexibility.
o To make amendments easily.
o For the design traceability.
o To increase efficiency.
The logical or physical connection among objects is referred to as link. These links are
used to relate multiple objects and represent a relationship between objects. We can not
reference links, because a link is not a component of either object by its own but do rely
on the objects.
The links in the above example represent the relationship between the different objects.
The links can be of three types – One-to-one, one-to-many, many-to-many.
Definition of Association
A collection of links is specified by an association which have common structure and semantics.
Association is essentially bidirectional. As the class describes the potential objects, in the similar
fashion an association represents a group of possible links.
Comparison Chart
between objects.
UML design Line segment between objects. Also uses line segment but it shows the
Generalization
In the generalization process, the common characteristics of classes are combined to form a class
in a higher level of hierarchy, i.e., subclasses are combined to form a generalized super-class. It
represents an “is – a – kind – of” relationship. For example, “car is a kind of land vehicle”, or
“ship is a kind of water vehicle”.
Specialization
Specialization is the reverse process of generalization. Here, the distinguishing features of groups
of objects are used to form specialized classes from existing classes. It can be said that the
subclasses are the specialized versions of the super-class.
The following figure shows an example of generalization and specialization.
Inheritance: Inheritance is the mechanism that permits new classes to be created out of
existing classes by extending and refining its capabilities. The existing classes are called the base
classes/parent classes/super-classes, and the new classes are called the derived classes/child
classes/subclasses. The subclass can inherit or derive the attributes and methods of the super-
class(es) provided that the super-class allows so. Besides, the subclass may add its own attributes
and methods and may modify any of the super-class methods. Inheritance defines an “is – a”
relationship.
Types of Inheritance
Single Inheritance − A subclass derives from a single super-class.
Multiple Inheritance − A subclass derives from more than one super-classes.
Multilevel Inheritance − A subclass derives from a super-class which in turn is derived from another
class and so on.
Hierarchical Inheritance − A class has a number of subclasses each of which may have subsequent
subclasses, continuing for a number of levels, so as to form a tree structure.
Hybrid Inheritance − A combination of multiple and multilevel inheritance so as to form a lattice
structure.
The following figure depicts the examples of different types of inheritance.
Aggregation((تجمع:
Aggregation or composition is a relationship among classes by which a class can be made
up of any combination of objects of other classes. It allows objects to be placed directly
within the body of other classes. Aggregation is referred as a “part–of” or “has–a”
relationship, with the ability to navigate from the whole to its parts. An aggregate object
is an object that is composed of one or more other objects.
Example
In the relationship, “a car has–a motor”, car is the whole object or the aggregate, and the
motor is a “part–of” the car. Aggregation may denote −
Physical containment − Example, a computer is composed of monitor, CPU,
mouse, keyboard, and so on.
Conceptual containment − Example, shareholder has–a share.
Abstract Classes :An abstract class is a class that is declared abstract—it may
or may not include abstract methods. Abstract classes cannot be instantiated, but they can
be subclassed.
If a class includes abstract methods, then the class itself must be declared abstract, as in:
When an abstract class is subclassed, the subclass usually provides implementations for all
of the abstract methods in its parent class. However, if it does not, then the subclass must
also be declared abstract.
Note: Methods in an interface (see the Interfaces section) that are not declared as default
or static are implicitly abstract, so the abstract modifier is not used with interface methods.
(It can be used, but it is unnecessary.)
Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix
of methods declared with or without an implementation. However, with abstract classes, you can
declare fields that are not static and final, and define public, protected, and private concrete
methods. With interfaces, all fields are automatically public, static, and final, and all methods that
you declare or define (as default methods) are public. In addition, you can extend only one class,
whether or not it is abstract, whereas you can implement any number of interfaces.
Consider using abstract classes if any of these statements apply to your situation:
o You want to share code among several closely related classes.
o You expect that classes that extend your abstract class have many common methods
or fields, or require access modifiers other than public (such as protected and
private).
o You want to declare non-static or non-final fields. This enables you to define
methods that can access and modify the state of the object to which they belong.
Consider using interfaces if any of these statements apply to your situation:
o You expect that unrelated classes would implement your interface. For example,
the interfaces Comparable and Cloneable are implemented by many unrelated
classes.
o You want to specify the behavior of a particular data type, but not concerned about
who implements its behavior.
o You want to take advantage of multiple inheritance of type.
An Abstract Class Example
In an object-oriented drawing application, you can draw circles, rectangles, lines, Bezier
curves, and many other graphic objects. These objects all have certain states (for
example: position, orientation, line color, fill color) and behaviors (for example: moveTo,
rotate, resize, draw) in common. Some of these states and behaviors are the same for all
graphic objects (for example: position, fill color, and moveTo). Others require different
implementations (for example, resize or draw). All GraphicObjects must be able to draw
or resize themselves; they just differ in how they do it. This is a perfect situation for an
abstract superclass. You can take advantage of the similarities and declare all the graphic
objects to inherit from the same abstract parent object (for example, GraphicObject) as
shown in the following figure.
1. Main difference is methods of a Java interface are implicitly abstract and cannot
have implementations. A Java abstract class can have instance methods that
implements a default behavior.
2. Variables declared in a Java interface is by default final. An abstract class may
contain non-final variables.
3. Members of a Java interface are public by default. A Java abstract class can have
the usual flavors of class members like private, protected, etc..
4. Java interface should be implemented using keyword “implements”; A Java
abstract class should be extended using keyword “extends”.
5. An interface can extend another Java interface only, an abstract class can extend
another Java class and implement multiple Java interfaces.
6. A Java class can implement multiple interfaces but it can extend only one abstract
class.
7. Interface is absolutely abstract and cannot be instantiated; A Java abstract class
also cannot be instantiated, but can be invoked if a main() exists.
8. In comparison with java abstract classes, java interfaces are slow as it requires
extra indirection.
Class can create a subclass that will inherit parent's properties and methods, whereas
Structure does not support the inheritance.
A class has all members private by default. A struct is a class where members
are public by default.
Classes allow to perform cleanup (garbage collector) before object is deallocated because
garbage collector works on heap memory. Objects are usually deallocated when instance
is no longer referenced by other code. Structures can not be garbage collector so no efficient
memory management.
Classes are still fit for larger or complex objects and Structs are good
for small, isolated model objects. Boxing and unboxing operations
are used to convert between a struct type and object. Too much
boxing and unboxing can have a negative impact on the heap, the
garbage collector, and ultimately the performance of the application.
In general, it's perfectly possible to create structs that look a lot like classes and classes that
look a lot like structs.
Which style you use depends on circumstances and taste. I usually prefer to use struct for
classes that have all data public. I think of such classes as "not quite proper types, just data
structures."
Section- C
Object oriented programming with C++
difference between C and C++:
1. When compared to C++, C is a subset of C++. All valid C programs are valid C++
programs.
2. C is a structural or procedural programming language, while C++ is an object
oriented programming language.
3. In C, Functions are the fundamental building blocks, while in C++, Objects are the
fundamental building blocks.
4. C doesn't have variable references, while C++ has variable references.
5. C uses malloc and free for memory allocation while C++ uses new and delete for
memory allocation.
6. C does not provide direct support for error handling, while C++ supports exception
handling that helps in error detection and smooth handling.
7. C does not support function and operator overloading, while C++ supports both
function and operator overloading.
8. C doesn't support Generic programming, while templates in C++ allow to write
generic programs.
9. C doesn't support namespaces while C++ supports them.
Difference between C and C++
C C++
C was developed by Dennis Ritchie between C++ was developed by Bjarne Stroustrup in
1969 and 1973 at AT&T Bell Labs. 1979 with C++'s predecessor "C with
Classes".
When compared to C++, C is a subset of C++ is a superset of C. C++ can run most
C++. of C code while C cannot run C++ code.
In C, data are free entities and can be In C++, Encapsulation hides the data to
manipulated by outside code. This is because ensure that data structures and operators are
C does not support information hiding. used as intended.
C does not support function and operator C++ supports both function and operator
overloading. overloading.
C does not allow functions to be defined inside In C++, functions can be used inside a
structures. structure.
C does not have namespace feature. C++ uses NAMESPACE which avoid
name collisions.
A namespace is a declarative region that
provides a scope to the identifiers (the
names of types, functions, variables, etc)
inside it. Namespaces are used to organize
code into logical groups and to prevent
name collisions that can occur especially
when your code base includes multiple
libraries. All identifiers at namespace scope
are visible to one another without
qualification. Identifiers outside the
namespace can access the members by
using the fully qualified name for each
identifier.
C uses functions for input/output. For C++ uses objects for input output. For
example scanf and printf. example cin and cout.
C does not support reference variables. C++ supports reference variables.
C has no support for virtual and friend C++ supports virtual and friend functions.
functions.
C provides malloc() and calloc()functions for C++ provides new operator for memory
dynamic memory allocation, and free() for allocation and delete operator for memory
memory de-allocation. de-allocation.
C does not provide direct support for error C++ provides support for exception
handling (also called exception handling) handling. Exceptions are used for "hard"
errors that make the code incorrect.
Object
This is the basic unit of object oriented programming. That is both data and function that operate
on data are bundled as a unit called as object.
Class
When you define a class, you define a blueprint for an object. This doesn't actually define any
data, but it does define what the class name means, that is, what an object of the class will consist
of and what operations can be performed on such an object.
Abstraction
Data abstraction refers to, providing only essential information to the outside world and hiding
their background details, i.e., to represent the needed information in program without presenting
the details.
For example, a database system hides certain details of how data is stored and created and
maintained. Similar way, C++ classes provides different methods to the outside world without
giving internal detail about those methods and data.
Encapsulation
Encapsulation is placing the data and the functions that work on that data in the same place. While
working with procedural languages, it is not always clear which functions work on which
variables but object-oriented programming provides you framework to place the data and the
relevant functions together in the same object.
Inheritance
One of the most useful aspects of object-oriented programming is code reusability. As the name
suggests Inheritance is the process of forming a new class from an existing class that is from the
existing class called as base class, new class is formed called as derived class.
This is a very important concept of object-oriented programming since this feature helps to reduce
the code size.
Polymorphism
The ability to use an operator or function in different ways in other words giving different
meaning or functions to the operators or functions is called polymorphism. Poly refers to many.
That is a single function or an operator functioning in many ways different upon the usage is
called polymorphism.
Data Hiding
A key feature of object oriented programming is 'data - hiding' i.e., the data is concealed within a class,
so that it cannot be accessed mistakenly by functions outside the class.
'private' and 'public' are two types of protection available within a class.
Items marked with 'private' can only be accessed by methods defined as part of the class. Data is most
often defined as private.
Private members can be accessed by members of the class.
Public items can be accessed from anywhere in the program without restrictions. Class methods are
usually public. As a general rule, data should not be declared public. Public members can be accessed
by members and objects of the class.
Protected is another type of protection available within a class. Items declared as protected are private
within a class and are available for private access in the derived class. The derived class concept is dealt
with later in this book. The protected access will be discussed again.
Example:
class fact{
int n,fct,temp;
public:
void read_data()
{
printf("Enter the Integer whose factorial you want to find\n");
scanf("%d", &n);
}
void calc_fact()
{
fct=1;
temp=n;
while (n>0)
{
fct=fct*n;
n--;
}
printf("Factorial of %d is %d \n",temp,fct);
}
};
void main()
{
fact f;
clrscr();
f.read_data();
f.calc_fact();
getch();
}
Note: As shown in the above example the variables n, fct and temp are private and can not be accessed
from the main function but can be accessed from the public functions read_data() and calc_data()
C++ Constructor
o Default constructor
o Parameterized constructor
1. #include <iostream>
2. using namespace std;
3. class Employee
4. {
5. public:
6. Employee()
7. {
8. cout<<"Default Constructor Invoked"<<endl;
9. }
10. };
11. int main(void)
12. {
13. Employee e1; //creating an object of Employee
14. Employee e2;
15. return 0;
16. }
Output:
#include <iostream>
using namespace std;
class Employee {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
Employee e2=Employee(102, "Nakul", 59000);
e1.display();
e2.display();
return 0;
}
Output:
// Constructor overloading {
{ construct o;
float area;
construct(){ o2.disp();
area = 0; } return 1;
#include <iostream>
using namespace std; int main(void) {
printData pd;
class printData {
public: // Call print to print integer
void print(int i) { pd.print(5);
cout << "Printing int: " << i << endl;
} // Call print to print float
void print(double f) { pd.print(500.263);
cout << "Printing float: " << f << endl;
} // Call print to print character
void print(char* c) { pd.print("Hello C++");
cout << "Printing character: " << c <<
endl; return 0;
} }
};
When the above code is compiled and executed, it produces the following result −
Printing int: 5
Printing float: 500.263
Printing character: Hello C++
+ - * / % ^
& | ~ ! , =
+= -= /= %= ^= &=
|= *= <<= >>= [] ()
:: .* . ?:
inline functions : C++ inline function is powerful concept that is commonly used with
classes. If a function is inline, the compiler places a copy of the code of that function at each point
where the function is called at compile time.
Any change to an inline function could require all clients of the function to be recompiled because
compiler would need to replace all the code once again otherwise it will continue with old
functionality.
To inline a function, place the keyword inline before the function name and define the function
before any calls are made to the function. The compiler can ignore the inline qualifier in case
defined function is more than a line.
A function definition in a class definition is an inline function definition, even without the use of
the inline specifier.
Following is an example, which makes use of inline function to return max of two numbers −
#include <iostream>
using namespace std;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Max (20,10): 20
Max (0,200): 200
Max (100,1010): 1010
};
class base
{ int main()
public: {
// in base
{
// Late binding (RTP)
//p->fun_4(5);
p->fun_4();
Output:
base-1
derived-2
base-3
base-4
Type of Inheritance
When deriving a class from a base class, the base class may be inherited through public,
protected or private inheritance. The type of inheritance is specified by the access-specifier as
explained above.
We hardly use protected or private inheritance, but public inheritance is commonly used. While
using different type of inheritance, following rules are applied −
Public Inheritance − When deriving a class from a public base class, publicmembers of the base class
become public members of the derived class and protected members of the base class
become protected members of the derived class. A base class's private members are never accessible
directly from a derived class, but can be accessed through calls to the public and protected members
of the base class.
Protected Inheritance − When deriving from a protected base class, public and protected members
of the base class become protected members of the derived class.
Private Inheritance − When deriving from a private base class, public and protected members of the
base class become private members of the derived class.
Multiple Inheritance
A C++ class can inherit members from more than one class and here is the extended syntax −
class derived-class: access baseA, access baseB....
Where access is one of public, protected, or private and would be given for every base class and
they will be separated by comma as shown above. Let us try the following example −
#include <iostream>
using namespace std; class Rectangle: public Shape, public
PaintCost {
// Base class Shape public:
class Shape { int getArea() {
public: return (width * height);
void setWidth(int w) { }
width = w; };
}
void setHeight(int h) { int main(void) {
height = h; Rectangle Rect;
} int area;
protected: Rect.setWidth(5);
int width; Rect.setHeight(7);
int height;
}; area = Rect.getArea();
reusable classes : C++ strongly supports the concept of reusability. The C++
classes can be reused in several ways. Once a class has been written and tested, it can be
adapted by another programmer to suit their requirements. This is basically done by
creating new classes, reusing the properties of the existing ones. The mechanism of
deriving a new class from an old one is called inheritance. The old class is referred to as
the base class and the new one is called the derived class or subclass. A derived class
includes all features of the generic base class and then adds qualities specific to the derived
class.
Abstract Classes
An abstract class is, conceptually, a class that cannot be instantiated and is usually
implemented as a class that has one or more pure virtual (abstract) functions.
A pure virtual function is one which must be overridden by any concrete (i.e., non-
abstract) derived class. This is indicated in the declaration with the syntax " = 0" in the
member function's declaration.
Example
class AbstractClass {
public:
virtual void AbstractMemberFunction() = 0; // Pure virtual function makes
// this class Abstract class.
virtual void NonAbstractMemberFunction1(); // Virtual function.
void NonAbstractMemberFunction2();
};
Example
class Vehicle {
public:
explicit
Vehicle( int topSpeed )
: m_topSpeed( topSpeed )
{}
int TopSpeed() const {
return m_topSpeed;
}
private:
int m_topSpeed;
};
private:
int m_numberOfWheels;
};
private:
int m_numberOfTracks;
};
In this example the Vehicle is an abstract base class as it has an abstract member
function.The class WheeledLandVehicle is derived from the base class. It also
holds data which is common to all wheeled land vehicles, namely the number of
wheels. The class TrackedLandVehicle is another variation of the Vehicle class.
This is something of a contrived example but it does show how that you can share
implementation details among a hierarchy of classes. Each class further refines a
concept. This is not always the best way to implement an interface but in some
cases it works very well. As a guideline, for ease of maintenance and understanding
you should try to limit the inheritance to no more than 3 levels. Often the best set
of classes to use is a pure virtual abstract base class to define a common interface.
Then use an abstract class to further refine an implementation for a set of concrete
classes and lastly define the set of concrete classes.
During the lectures, I would periodically pose a question, which the attendees could answer via
the chat. An interesting one was: how does a struct differ from a class in C++? …
But what about a struct in C++? The last example here gives a clue. The only difference
between a struct and class in C++ is the default accessibility of member variables and methods.
In a struct they are public; in a class they are private.
Having imparted this information, I urge you not to exploit it too heavily. A key priority when
you are writing code is to ensure that it is readable [=maintainable]. Somebody – it could be you
– might need to look at this code in a year’s time and understand what it does. I have heard
advice as follows: Assume that the person that will maintain
your code is an armed psychopath, who has limited patience and
knows your home address.
Section- D
Object oriented programming with Java
Introduction to java
Java is a high-level programming language originally developed by Sun Microsystems
and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and
the various versions of UNIX. This tutorial gives a complete understanding of Java. This
reference will take you through simple and practical approaches while learning Java
Programming language.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun, Java language is a simple programming language because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
Object-oriented
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc.
which are compiled into platform specific machines while Java is a write once, run
anywhere language. A platform is the hardware or software environment in which a
program runs.
There are two types of platforms software-based and hardware-based. Java provides a
software-based platform.
The Java platform differs from most other platforms in the sense that it is a software-
based platform that runs on the top of other hardware-based platforms. It has two
components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be run on multiple platforms, for example, Windows, Linux, Sun Solaris,
Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode. This
bytecode is a platform-independent code because it can be run on multiple platforms, i.e.,
Write Once and Run Anywhere(WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
Java language provides these securities by default. Some security can also be provided by
an application developer explicitly through SSL, JAAS, Cryptography, etc.
Robust
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4
bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both
32 and 64-bit architectures in Java.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It
doesn't require any implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language
(e.g., C++). Java is an interpreted language that is why it is slower than compiled
languages, e.g., C, C++, etc.
Distributed
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs
that deal with many tasks at once by defining multiple threads. The main advantage of
multi-threading is that it doesn't occupy memory for each thread. It shares a common
memory area. Threads are important for multi-media, Web applications, etc.
Dynamic
Java is a dynamic language. It supports dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++.
Java also adds some new features, while C++ is a superset of C, Java is neither a superset
nor a subset of C or C++.
Java and C
Java is not lot like C but the major difference between Java and C is that Java is an object-
oriented language and has a mechanism to define classes and objects. In an effort to build
a simple and safe language, the Java team did not include some of the C features in Java.
1. Java does not include the C unique statement keywords size of and typedef.
2. Java does not contain the data type struct and union.
3. Java does not define the type modifiers keywords auto, extern, register, signed, and unsigned.
4. Java does not support an explicit pointer type.
5. Java does not have a preprocessor and therefore we cannot use # define, # include, and # ifdef
statements.
6. Java requires that the functions with no arguments must be declared with empty parenthesis
and not with the void keyword as done in C.
7. Java adds new operators such as instanceof and >>>.
8. Java adds labelled break and continue statements.
9. Java adds many features required for object-oriented programming.
C Programming Java Programming
It does include the unique statement keywords It does not include the C unique statement keywords sizeof,
sizeof, and typedef. and typedef.
It contain the data type struct and union. It does not contain the data type struct and union.
It define the type modifiers keywords auto, It does not define the type modifiers keywords auto, extern,
extern, register, signed, and unsigned. register, signed, and unsigned.
It supports an explicit pointer type. It does not support an explicit pointer type.
It has a preprocessor and therefore we can use It does not have a preprocessor and therefore we cannot use
# define, # include, and # ifdef statements. # define, # include, and # ifdef statements.
It requires that the functions with no It requires that the functions with no arguments must be
arguments, with the void keyword declared with empty parenthesis, not with the void keyword
C has no operators such as instanceof and Java adds new operators such as instanceof and >>>.
>>>.
C adds have a break and continue statements. Java adds labeled break and continue statements.
C has no object-oriented programming Java adds many features required for object-oriented
features. programming.
It support has template classes. It does not have template classes as in C++.
It supports multiple inheritances of It does not support multiple inheritances of classes. This is
classes. accomplished using a new feature called “Interface”.
It supports global variables. It does not support global variables. Every variable and method is
declared within classes and forms part of that class.
It does not support destructor function It has replaced the destructor function with a finalize() function.
with a finalize() function.
There are header files in Java. There are no header files in Java.
Datatypes: union,
Supported Supported Not Supported
structure
Supported (#include, Supported (#include,
Pre-processor directives Not Supported
#define) #define)
Storage Allocation Uses malloc, calloc Uses new, delete uses garbage collector
Multithreading and
Not Supported Not Supported Supported
Interfaces
7. Java communicate with a web page through a special tag called <applet>.
8. Java user sends a request for an HTML document to the remote computers net
browser.
9. The web-browser is a program that accepts a request, process the request and
sends the required documents.
10. The HTML document is returned to that user browser.
11. The document contains the applet tag which identifies the applet.
12. The corresponding applet is transferred to the user computer.
13. The Java enabled browser on the users computer interprets the byte code and
provide output.
Web Browsers
The internet is a vast sea of information represented in many formants and store on many
computers. a browser is a software application used to locate, retrieve and display content
on the World Wide Web, including Web pages, images, video and other files. As a
client/server model, the browser is the client run on a computer that contacts the Web server
and requests information. The Web server sends the information back to the Web browser
which displays the results.
The browser application retrieves or fetches code, usually written in HTML (HyperText
Markup Language) and/or another language, from a webserver, interprets this code, and
renders (displays) it as a Web page for you to view. on the computer or other Internet-
enabled device that supports a browser.
Example of Web Browsers:
Hot Java
Netscape Navigator
Internet Explorer
Google Chorme
o Install the JDK if you don't have installed it, download the JDK and install it.
o Set path of the jdk/bin directory. http://www.javatpoint.com/how-to-set-path-in-java
o Create the java program
o Compile and run the java program
class Simple{
public static void main(String args[]){ System.out.println("Hello Java"); }}
Let's see what is the meaning of class, public, static, void, main, String[],
System.out.println().
o class keyword is used to declare a class in java.
o public keyword is an access modifier which represents visibility. It means it is
visible to all.
o static is a keyword. If we declare any method as static, it is known as the static
method. The core advantage of the static method is that there is no need to create
an object to invoke the static method. The main method is executed by the JVM,
so it doesn't require to create an object to invoke the main method. So it saves
memory.
o void is the return type of the method. It means it doesn't return any value.
o main represents the starting point of the program.
o String[] args is used for command line argument. We will learn it later.
o System.out.println() is used to print statement. Here, System is a class, out is the
object of PrintStream class, println() is the method of PrintStream class. We will
learn about the internal working of System.out.println statement later.
1. public static void main(String[] args) 5. static public void main(String[] args)
2. public static void main(String []args) 6. public static final void main(String[] args)
3. public static void main(String args[]) 7. final public static void main(String[] args)
4. public static void main(String... args) 8. final strictfp public static void main(String[] args)
Syntax
modifier class myClass { //class header
//field, constructor
//method declarations };
Notes
The class body contains constructors for initializing new objects, declarations for the fields that provide
the state of the class and its objects, and methods to implement the behaviour of the class and its objects.
Example
public class Bike {
//fields:
public int speed;
public int gear;
//Constructor:
public Bike(int startSpeed, int startGear) {
this.gear = startGear;
this.speed = startSpeed; }
//Methods:
public void setGear (int newValue) {
this.gear = newValue; }
public void applyBrake(int decrement) {
this.speed -= decrement; }
public void speedUp(int increment) {
this.speed += increment;
}
}
Braces, also known as curly braces, use { and } to delimit compound statements. Also, Java
uses them for surrounding the bodies of loops, methods and classes.
For example
Instance initializer, it is a block of code that will execute each time an instance of the class is
created.
class Program {
{ System.out.println("Instance Intializer");
}public static void main(String[] args) {}}
Static initializer, it is a block of code that will execute only one time when the class is first
loaded.
class Program {
static {
System.out.println("Instance Intializer");
} public static void main(String[] args) {
}}
A compound statement, it is just a block of code that will execute when the method is invoked.
class Program {
public static void main(String[] args) {
{ ....
System.out.println("Inside method");
.... } }}
Local variables are declared within code blocks. The scope of a local variable starts at the
variable declaration and ends at the closing curly brace of the containing block.
Java main method is the entry point of any java program. Its syntax is always public
static void main(String[] args) . You can only change the name of String array argument, for
example you can change args to myStringArgs.
Also String array argument can be written as String... args or String args[].
Let’s look at the java main method closely and try to understand each of its parts.
public
This is the access modifier of the main method. It has to be public so that java runtime
can execute this method. Remember that if you make any method non-public then it’s
not allowed to be executed by any program, there are some access restrictions applied.
So it means that the main method has to be public. Let’s see what happens if we
define the main method as non-public.
public class Test { static void main(String[] args){ System.out.println("Hello World"); } }
$ javac Test.java
$ java Test
Error: Main method not found in class Test, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application $
static
When java runtime starts, there is no object of the class present. That’s why the main
method has to be static so that JVM can load the class into memory and call the main
method. If the main method won’t be static, JVM would not be able to call it because
there is no object of the class is present. Let’s see what happens when we remove
static from java main method.
void
Java programming mandates that every method provide the return type. Java main
method doesn’t return anything, that’s why it’s return type is void. This has been done
to keep things simple because once the main method is finished executing, java
program terminates. So there is no point in returning anything, there is nothing that
can be done for the returned object by JVM. If we try to return something from the
main method, it will give compilation error as an unexpected return value. For
example, if we have the main method like below.
public class Test {
public static void main(String[] args){
return 0;}}
This is the name of java main method. It’s fixed and when we start a java program, it
looks for the main method. For example, if we have a class like below.
$ javac Test.java
$ java Test
Error: Main method not found in class Test, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application $
String[] args
Java main method accepts a single argument of type String array. This is also called as
java command line arguments. Let’s have a look at the example of using java
command line arguments.
Above is a simple program where we are printing the command line arguments. Let’s
see how to pass command line arguments when executing above program.
$ javac Test.java
$ java Test 1 2 3
1
2
3
$ java Test "Hello World" "Pankaj Kumar"
Hello World
Pankaj Kumar
$ java Test
$
Java Output
You can simply use System.out.println(), System.out.print() or System.out.printf() to send output to
standard output (screen).
System is a class and out is a public static field which accepts output data. Don't worry if you don't
understand it. Classes, public, and static will be discussed in later chapters.
1. class AssignmentOperator {
2. public static void main(String[] args) {
3.
4. System.out.println("Java programming is interesting.");
5. }
6. }
We must save this program in a file called Javaapp.java ensuring that the file name
contains the class name properly. This file is called the source file. Note that all Java
source files will have the extension java.
Java breaks all these restriction, Java gives the freedom to write and compile the program
in any platform or machine and the same program can run on different platform and
machine. Example Java program written for Linux system can also run on windows and
UNIX etc.
What it does
The JVM performs following operation:
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.
JVM Architecture
Let's understand the internal architecture of JVM. It contains classloader, memory area,
execution engine etc.
1) Classloader
Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it is loaded
first by the classloader. There are three built-in classloaders in Java.
1. Bootstrap ClassLoader : This is the first classloader which is the super class of Extension classloader. It
loads the rt.jar file which contains all class files of Java Standard Edition like java.lang package classes,
java.net package classes, java.util package classes, java.io package classes, java.sql package classes etc.
2. Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of System
classloader. It loades the jar files located inside $JAVA_HOME/jre/lib/ext directory.
3. System/Application ClassLoader: This is the child classloader of Extension classloader. It loads the
classfiles from classpath. By default, classpath is set to current directory. You can change the classpath
using "-cp" or "-classpath" switch. It is also known as Application classloader.
Output:
sun.misc.Launcher$AppClassLoader@4e0e2f2a
null
These are the internal classloaders provided by Java. If you want to create your own classloader, you need to extend
the ClassLoader class.
2) Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code for
methods.
3) Heap
It is the runtime data area in which objects are allocated.
4) Stack
Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation and
return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.
7) Execution Engine
It contains:
1. A virtual processor
2. Interpreter: Read bytecode stream then execute the instructions.
3. Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the byte code
that have similar functionality at the same time, and hence reduces the amount of time needed for
compilation. Here, the term "compiler" refers to a translator from the instruction set of a Java virtual
machine (JVM) to the instruction set of a specific CPU.
Example While running a class Demo, you can specify command line arguments as
class Demo{
Section Description
Documentation You can write a comment in this section. Comments are beneficial for
Section the programmer because they help them understand the code. These
are optional, but we suggest you use them because they are useful to
understand the operation of the program, so you must write comments
within the program.
Package You can create a package with any name. A package is a group of
statement classes that are defined by a name. That is, if you want to declare many
classes within one element, then you can declare it within a package. It
is an optional part of the program, i.e., if you do not want to declare any
package, then there will be no problem with it, and you will not get any
errors. Here, the package is a keyword that tells the compiler that
package has been created.It is declared as:
package package_name;
Import This line indicates that if you want to use a class of another package,
statements then you can do this by importing it directly into your program.
Example:import calc.add;
Interface Interfaces are like a class that includes a group of method declarations.
statement It's an optional section and can be used when programmers want to
implement multiple inheritances within a program.
Class A Java program may contain several class definitions. Classes are the
Definition main and essential elements of any Java program.
Main Method Every Java stand-alone program requires the main method as the
Class starting point of the program. This is an essential part of a Java
program. There may be many classes in a Java program, and only one
class defines the main method. Methods contain data type declaration
and executable statements.
public class Hello{
/* Author: www.w3schools.in Writes the words "Hello Java" on the screen */
public static void main(String[] args){
System.out.println("Hello Java"); }
Let's Look into Various Parts of the Above Java Program
/* Comments */ The compiler ignores comment block. Comment can be used anywhere in the
program to add info about the program or code block, which will be helpful for
developers to understand the existing code in the future easily.
Braces Two curly brackets {...} are used to group all the commands, so it is known that the
commands belong to that class or method.
public static void When the main method is declared public, it means that it can also be used by
main code outside of its class, due to which the main method is declared public.
The word static used when we want to access a method without creating its
object, as we call the main method, before creating any class objects.
The word void indicates that a method does not return a value. main() is declared
as void because it does not return a value.
main is a method; this is a starting point of a Java program.
You will notice that the main method code has been moved to some spaces
left. It is called indentation which used to make a program easier to read and
understand.
String[] args It is an array where each element of it is a string, which has been named as "args".
If your Java program is run through the console, you can pass the input parameter,
and main() method takes it as input.
System.out.println(); This statement is used to print text on the screen as output, where the system is a
predefined class, and out is an object of the PrintWriter class defined in the system.
The method println prints the text on the screen with a new line. You can also
use print() method instead of println() method. All Java statement ends with a
semicolon.
Java Program Structure: A Java program consists of different sections. Some of them
are mandatory but some are optional. The optional section can be excluded from the
program depending upon the requirements of the programmer.
Documentation Section
It includes the comments to tell the program's purpose. It improves the readability of the
program.
Package Statement
It includes statement that provides a package declaration.
Import statements
It includes statements used for referring classes and interfaces that are declared in other
packages.
Interface Section
It is similar to a class but only includes constants, method declaration.
Class Section
It describes information about user defines classes present in the program. Every Java
program consists of at least one class definition. This class definition declares the main
method. It is from where the execution of program actually starts.
1. Documentation Section: It includes the comments that improve the readability of the
program. A comment is a non-executable statement that helps to read and understand a
program especially when your programs get more complex. It is simply a message that
exists only for the programmer and is ignored by the compiler. A good program should
include comments that describe the purpose of the program, author name, date and time of
program creation. This section is optional and comments may appear anywhere in the
program.
Java programming language supports three types of comments.
Single line (or end-of line) comment: It starts with a double slash symbol (//) and
terminates at the end of the current line. The compiler ignores everything from // to the end
of the line. For example:
// Calculate sum of two numbers
Multiline Comment: Java programmer can use C/C++ comment style that begins with
delimiter /* and ends with */. All the text written between the delimiter is ignored by the
compiler. This style of comments can be used on part of a line, a whole line or more
commonly to define multi-line comment. For example.
/*calculate sum of two numbers */
Comments cannot be nested. In other words, you cannot comment a line that already
includes traditional comment. For example,
/* x = y /* initial value */ + z; */ is wrong.
Documentation comments: This comment style is new in Java. Such comments begin
with delimiter /** and end with */. The compiler also ignores this type of comments just
like it ignores comments that use / * and */. The main purpose of this type of comment is
to automatically generate program documentation. The java doc tool reads these comments
and uses them to prepare your program's documentation in HTML format. For example.
/**The text enclosed here will be part of program documentation */
Package Statement: Java allows you to group classes in a collection known as package.
A package statement includes a statement that provides a package declaration. It must
appear as the first statement in the source code file before any class or interface declaration.
This statement is optional. For example: Suppose you write the following package
declaration as the first statement in the source code file.
package employee;
This statement declares that all classes and interfaces defined in this source file are part of
the employee package. Only one package declaration can appear in the source file.
Import Statement: Java contains many predefined classes that are stored into packages.
In order to refer these standard predefined classes in your program, you need to use fully
qualified name (i.e. Packagename.className). But this is a very tedious task as one need
to retype the package path name along with the classname. So a better alternative is to use
an import statement.
An import statement is used for referring classes that are declared in other packages. The
import statement is written after a package statement but before any class definition. You
can import a specific class or all the classes of the package. For example : If you want to
import Date class of java.util package using import statement then write
import java.util.Date;
This statement allows the programmer to use the simple classname Date rather than fully
qualified classname java.util.Date in the code.
Unlike package statement, you can specify more than one import statement in your
program.
For example:
Import java.util.Date; /* imports only the Date class in java.util package */
import java.applet.*; // imports all the classes in java applet
// package
Interface Section: In the interface section, we specify the interfaces. An interface is similar
to a class but contains only constants and method declarations. Interfaces cannot be
instantiated. They can only be implemented by classes or extended by other interfaces. It
is an optional section and is used when we wish to implement multiple inheritance feature
in the program.
interface stack {
void push(int item); // Insert item into stack
int pop(); // Delete an item from stack
}
Class Section: The Class section describes the information about user-defined classes
present in the program. A class is a collection of fields (data variables) and methods that
operate on the fields. Every program in Java consists of at least one class, the one that
contains the main method. The main () method which is from where the execution of
program actually starts and follow the statements in the order specified.
The main method can create objects, evaluate expressions, and invoke other methods and
much more. On reaching the end of main, the program terminates and control passes back
to the operating system.
The class section is mandatory.
After discussing the structure of programs in Java, we shall now discuss a program that
displays a string Hello Java on the screen.
// Program to display message on the screen
class HelloJava {
public static void main(String args[]){
System.out.println("Hello Java");
}
}
Program'sExplanation:
1. The first line of the program begins with //, indicating that the remainder of the line is a
comment. It describes the purpose of the program.
2. Since Java is an object-oriented language, so everything in a Java program resides inside
a class. In our program, the second line
classFirstProg
defines a class named FirstProg. The keyword class before the class name identifies that it
is a class definition. By convention, begin the class name with an uppercase letter and each
subsequent word in a class name with an uppercase letter. The naming of the class must
follow the same rules as for naming of any other identifier.
3. The opening curly brace ({) after the class name as in line 3 tells the compiler from
where does the body of the class begin. The closing curly brace (}) in line 8 tells the
compiler where does the body of class ends. Any code between these braces is considered
to be part of FirstProg class. Note that lines between these braces are indented which is
considered a good programming practice.
4. The lines 4 through 7 defines a method main () of the FirstProg class which serves as
the entry point for the program execution. A method contains a collection of programming
instructions that describe how to carry out a particular task. Line 4 specifies the main ()
method header which must always be written as
public static void main(String[] args)
We shall now discuss the various terms used in the method header,
• public: The public keyword is an access specifier which indicates that the method
declared here should have public access, i.e. anyone can invoke it such as Java Virtual
Machine (JVM). All Java programs must have at least one class that declares a public
method named main. The JVM will start the execution of the program at the first statement
of the main method and terminates execution after the last statement.
• static: The keyword static allows main () to called before an object of the class has
created. This is necessary since main () is called by the JVM before any objects are made.
Since it is static, it can be invoked directly from a class.
• void: The type modifier void indicates that the main () method is declared does not return
a value.
• string [] args: The argument String [] args is the only parameter in the main method. The
String [] args declares a parameter named args which contains an array of objects of the
class type String. The args receive any command-line arguments present when the program
executed.
5. The code for the main method appears between the pair of curly braces. In our program,
this method contains only one executable statement.
System.out.println("Welcome to Java");
This statement displays a message Welcome to Java in the command window.
This statement might look a little confusing the first time so to help make things clearer
let's examine the statement from left to right.
• System: It is the name of the standard class that contain objects that encapsulates the
standard I/O devices for your system. It contained in the package java.lang. Since java.lang
is imported in every Java program by default; therefore the java.lang is the
only package in the Java API that does not require an import declaration.
• out: The object out represents the standard output stream (i.e. command window) and is
a static data member of the class System. To refer the out member of the System class write
System.out.
• println(): The println() is the method of out object that takes the text string as an argument
and displays it to the standard output, i.e. monitor's screen. It then terminates the output
line so that each call to println () displays its output on a new line.
A method is invoked by supplying an object reference (in this case System. out) and a
method name (println() ) separated by the dot(.). It demonstrates one way in which you can
call a class method.
The semicolon at the end of this statement specifies the end of the statement. Every
statement in Java must end with a semicolon (;).
On executing this Java program, a message Welcome to Java would be displayed on the
screen.
NOTE: In addition to println() method, System.out also has a print() method that displays
a string but unlike println() method, the cursor does not move to the beginning of the next
line after displaying the string.