Unit 1 2022 OOP-1
Unit 1 2022 OOP-1
Unit 1 2022 OOP-1
1.Overview of OOP
The major motivating factor in the invention of object-oriented approach is to remove some of the
flaws encountered in the procedural approach.
OOP treats data as a critical element in the program development and does not allow it to flow
freely aroundthe system. It ties data more closely to the function that operate on it, and protects
itfrom accidental modification from outside function.
OOP allows decomposition of aproblem into a number of entities called objects and then builds data
and functionaround these objects.
3. The software is divided into a number of small units called objects. The data and functions
are built around these objects.
4. The data of the objects can be accessed only by the functions associated with that object.
5. The functions of one object can access the functions of another object.
Software re-use: where an application can be composed from existing and new modules.
To support the principles of object-oriented programming, all OOP languages, have the following
characteristics
1.2 Features of Object Oriented Programming
Abstraction
Abstraction refers to the act of representing essential features without including the background
details or explanation.
Abstraction is one of the key concepts of object-oriented programming (OOP) languages.
Data Abstraction can be defined as the process of identifying only the required(essential)
characteristics of an object ignoring the irrelevant details.
Abstraction is a process of hiding the implementation details and showing only functionality
to the user.
Its main goal is to handle complexity by hiding unnecessary details from the user. That
enables the user to implement more complex logic on top of the provided abstraction without
understanding or even thinking about all the hidden complexity.
Abstraction is a process where you show only “relevant” data and “hide” unnecessary details
of an object from the user.
Example1:
when you login to your bank account online, you enter your user_id and password and press
login, what happens when you press login, how the input data sent to server, how it gets
verified is all abstracted away from the you.
Example2:
When you press a key on your keyboard the character appears on the screen, you need to
know only this, but how exactly it works based on the electronically is not needed.
This is called Abstraction.
• Abstraction is achieved by using Interface and abstract class in java
Encapsulation
The wrapping up of data and functions into a single unit (called class) is known as Encapsulation.
Data Encapsulation is the most striking feature of a class.
The data is not accessible to the outside world, and only those functions which are wrapped
in the class can access it.
These functions provide the interface between the object’s data and the program.
Encapsulation is a process of combining data and function into a single unit like capsule.
This is to avoid the access of private data members from outside the class.
Inheritance
Inheritance is the process by which one object acquires the properties of another object.
The mechanism of deriving a new class from existing/old class is called “inheritance”.
The old class is known as “base” class, “super” class or “parent” class”; and the new
class is known as “sub” class, “derived” class, or “child” class.
Thisis important because it supports the concept of hierarchical classification. (that is, top-
down classifications.)
For example, a Golden Retriever is part of the classification dog, which in turn is part of
themammal class, which is under the larger class animal. Without the use of hierarchies,
eachobject would need to define all of its characteristics explicitly.
Using inheritance, an object need only define those qualities that make it unique within its
class. It can inherit its general attributes from its parent. Thus, it is the inheritance mechanism
that makes it possible for one object to be a specific instance of a more general case
Polymorphism
Polymorphism,a Greek term ,means the ability to take more than one form.
In Java, polymorphism refers to the fact that you can have multiple methods with the
same name in the same class.
Method Overriding
If a derived class has a method found within its base class, that method will override the base
class’s method
The keyword super can be used to gain access to superclass methods overridden by the
base class
A subclass method must have the same return type as the corresponding superclass
Method.This is called overriding a method
Method print in Dog overrides method print in Animal
A subclass variable can shadow a superclass variable, but a subclass method can
override a superclass method.
Example
class Animal
{
void print()
{
System.out.println("Superclass Animal");
}
}
Overriding vs Overloading
A method is overloaded if it has multiple definitions that are distinguished from one
another by having different numbers or types of arguments
A method is overridden when a subclass gives a different definition of the method with
the same number and types of arguments
1.Simple
Java is very easy to learn and its syntax is simple, clean and easy to understand.
Java syntax is based on C++ (so easier for programmers to learn it after C++).
Java has removed many confusing and rarely-used features e.g. explicit pointers, operator
overloading etc.
There is no need to remove unreferenced objects because there is Automatic Garbage Collection
in java.
2.Object-oriented programming
Java is object-oriented programming language. Everything in Java is an object. Object-
oriented means we
organize our software as a combination of different types of objects that incorporates both data
and behaviour.
3.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
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.
4.Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured
because:
No explicit pointer. Java Programs run inside virtual machine sandbox
5.Java is robust
It uses strong memory management.
6.Architecture neutral
Java is architecture neutral because there is no implementation dependent features e.g. 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.
But in java, it occupies 4 bytes of memory for both 32 and 64 bit architectures.
7.Portable
Java is portable because it facilitates you to carry the java bytecode to any platform. It doesn't
require any type of implementation.
8.High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode is
"close" to native code. (JIT)
9.Distributed
Java is distributed because it facilitates users to create distributed applications in java. RMI and
EJB are used for creating distributed applications.
This feature of Java makes us able to access files by calling the methods from any machine on
the internet.
10.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.
Objects are dynamically allocated by using the new operator, dynamically allocated objects
must be manually released by use of a delete operator.
11.Garbage collection
Java takes a different approach; it handles deallocation automatically this is called garbage
collection.
When no references to an object exist, that object is assumed to be no longer needed, and the
memory occupied by the object can be reclaimed.
3. OVERVIEW OF JAVA
JAVA was developed by James Gosling at Sun Microsystems Inc in the year 1995, later
acquired by Oracle Corporation.
It is a simple programming language. Java makes writing, compiling, and debugging
programming easy.
It helps to create reusable code and modular programs. Java is a class-based, object-oriented
programming language and is designed to have as few implementation dependencies as
possible.
A general-purpose programming language made for developers to write once run anywhere
that is compiled Java code can run on all platforms that support Java.
Java applications are compiled to byte code that can run on any Java Virtual Machine. The
syntax of Java is similar to c/c++
Java Environment
JRE
• JRE is an acronym for Java Runtime Environment.
• .The Java Runtime Environment is a set of software tools which are used for developing java
applications.
• It is used to provide runtime environment.
• It is the implementation of JVM. It physically exists.
• It contains set of libraries + other files that JVM uses at runtime
• The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as
an interpreter/loader (Java),
• compiler (javac),
• archiver (jar),
• a documentation generator (Javadoc) etc
Setting up Java Environment: After installing the JDK, we need to set at least oneenvironment
variable in order to able to compile and run Java programs.
A PATH environment variable enables the operating system to find the JDK executables when
ourworking directory is not the JDK's binary directory.
Setting environment variables from a command prompt: If we set the variables from a command
prompt, they will only hold for that session.
To set the PATH from acommand prompt:
set PATH=C:\Program Files\Java\jdk1.5.0_05\bin;
Data Types: The classification of data item is called data type. Java defines eight simple types
ofdata. byte, short, int, long, char, float, double and boolean. These can be put in four groups:
3.Character Data Type: This data type represents a single character. char data type injava uses
two bytes of memory also called Unicode system. Unicode is a specification to include alphabets of
all international languages into the character set of java.
4.Boolean Data Type: can handle truth values either true or falsee.g.:-
boolean response = true;
Variables in Java
A variable is the name given to a memory location. It is the basic unit of storage in a program.
The value stored in a variable can be changed during program execution.
A variable is only a name given to a memory location, all the operations done on the variable
effects that memory location.
In Java, all the variables must be declared before they can be used.
1. A variable name can consist of Capital letters A-Z, lowercase letters a-z, digits 0-9, and two
special characters such as underscore and dollar Sign.
2. Variable name can begin with special characters such as $ and _
As per the java coding standards,the first character must be a letter.
3. Blank spaces cannot be used in variable names.
4. Java keywords cannot be used as variable names.
5. Variable names are case-sensitive
2) Instance Variable
A variable declared inside the class but outside the method, is called instance variable . It is not
declared as static.
3) Static variable
A variable which is declared as static is called static variable. It cannot be local.
Sample Program 1:
public class StudentDetails
{
public void StudentAge()
{ //local variable age
int age = 0;
age = age + 5;
System.out.println("Student age is : " + age);
}
Output:
error: cannot find symbol”+ age
2.Instance Variables:
A variable declared inside the class but outside the method, is called instance variable. It is not
declared as static.
Instance variables are non-static variables and are declared in a class outside any method,
constructor or block.
class MarksDemo
{
public static void main(String args[])
{ //first object
Marks obj1 = new Marks();
obj1.mathsMarks = 80;
obj1.phyMarks = 90;
//second object
Marks obj2 = new Marks();
obj2.mathsMarks = 60;
obj2.phyMarks = 85;
Output:
Marks for first object:
80
90
Marks for second object:
60
85
As you can see in the above program the variables mathsMarks , phyMarksare instance
variables.
In case we have multiple objects as in the above program, each object will have its own
copies of instance variables.
It is clear from the above output that each object will have its own copy of instance variable.
3.Static Variables:
A variable which is declared as static is called static variable. It cannot be local.
Static variables are also known as Class variables.
To access static variables, we need not to create any object of that class, we can simply access the
variable as:
class_name.variable_name;
Sample Program:
import java.io.*;
class Emp
{
}
output:
Harsh's average salary:1000.0
Arrays
An array represents a group of elements of same data type. Arrays are generallycategorized into two
types:
We can create a 1D array by declaring the array first and then allocate memory for it by
using new operator, as:
int marks[]; //declare marks array
marks = new int[5];//allot memory for storing 5 elements
//printing array
for(int i=0;i<a.length;i++)
System.out.print(a[i]);
}}
Output:
33 3 4 5
Passing Array to method in java
We can pass the java array to method so that we can reuse the same logic on any array.
Example:
class Testarray2
{
static void min(int arr[])
{
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[])
{
int a[]={33,3,4,5};
min(a);//passing array to method
}
}
o We can declare a two dimensional array and directly store elements at the time ofits
declaration, as:
int marks[] [] = {{50, 60, 55, 67, 70},{62, 65, 70, 70, 81}, {72, 66, 77, 80, 69} };
We can create a two dimensional array by declaring the array first and then we can allotmemory
for it by using new operator as:
These two statements also can be written as: int marks [ ][ ] = new int[3][5];
Program 2: Write a program to take a 2D array and display its elements in the form of a
matrix. //Displaying a 2D array as a matrix
class Matrix
{
public static void main(String args[])
{
//take a 2D array
int x[ ][ ] = {{1, 2, 3}, {4, 5, 6} };
// display the array elements
for (int i = 0 ; i < 2 ; i++)
{
System.out.println (); for (int j = 0 ; j < 3 ; j++)
System.out.print(x[i][j] + “\t”);
}
}
}
Three Dimensional arrays (3D arrays)
We can consider a three dimensional arrayas a combination of several two dimensional arrays. To
represent a three dimensional array, we should use three pairs of square braces [ ] [ ] after the array
name.
o We can declare a three dimensional array and directly store elements at the time ofits
declaration, as:
int arr[ ] [ ] [ ] = {{{50, 51, 52},{60, 61, 62}}, {{70, 71, 72}, {80, 81, 82}}};
o We can create a three dimensional array by declaring the array first and then we can allot
memory for it by using new operator as:
1. Arithmetic Operators
2. Relational Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
1.Arithmetic operators: These operators are used to perform fundamental operationslike addition,
subtraction, multiplication etc.
+ Addition 3+4 7
- Subtraction 5-7 -2
* Multiplication 5*5 25
2.Assignment operator: This operator (=) is used to store some value into a variable.
x=x+y x += y
x=x–y x -= y
x=x*y x *= y
x=x y x /= y
3. Unary operators: As the name indicates unary operator’s act only on one operand.
First Expression1 is evaluated. If it is true, then Expression2 value is stored into variable otherwise
Expression3 value is stored into the variable.
e.g.: max = (a>b) ? a: b;
Sum : 19
Difference : 11
Product : 60
Quotient : 3
Remainder : 3
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}
Output
a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
b <= a = false
4.Logical Operators
class Logicalop
{
public static void main(String[] args)
{
// && operator
System.out.println((5 > 3) && (8 > 5)); // true
System.out.println((5 > 3) && (8 < 5)); // false
// ! operator
System.out.println(!(5 == 3)); // true
System.out.println(!(5 > 3)); // false
}
}
Output
truefalse
true
true
false
true
false
5.Bitwise Operators
class Test
{
c = a | b; /* 61 = 0011 1101 */
System.out.println("a | b = " + c );
c = a ^ b; /* 49 = 0011 0001 */
System.out.println("a ^ b = " + c );
c = a >> 2; /* 15 = 1111 */
System.out.println("a >> 2 = " + c );
6. Control Statements
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
1.if Statement
• if statement is the most simple decision making statement.
• It is used to decide whether a certain statement or block of statements will be executed
or not that is if a certain condition is true then a block of statement is executed otherwise not.
Syntax:
if(condition)
{
//statements to execute if
//condition is true
}
3.Nested if Statement
Nested if-else statements, is that using one if or else if statement inside another if or else if statement
Example:
// Java program to illustrate nested-if statement
class NestedIfDemo
{
public static void main(String args[])
{
int i = 10;
if (i == 10)
{
if (i < 15)
System.out.println("i is smaller than 15");
if (i < 12)
System.out.println("i is smaller than 12 too");
else
System.out.println("i is greater than 15");
}
}
}
Output:
i is smaller than 15
i is smaller than 12
Example:
public class IfElseIfExample
{
public static void main(String[] args)
{
int marks=65;
if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60)
{
System.out.println("D grade");
5.Switch Statements
The switch statement is Java’s multiway branch statement. It provides an easy way to dispatch
execution to different parts of your code based on the value of an expression.
Syntax:
switch (expression)
{
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
.
.
case valueN :
// statement sequence
break;
default:
// default statement sequence
}
Example:
// A simple example of the switch.
class SampleSwitch
{
public static void main(String args[])
{
for(int i=0; i<6; i++)
switch(i)
{
case 0:
System.out.println("i is zero.");
break;
Example:
// Demonstrate the while loop.
class While {
public static void main(String args[]) {
int n = 5;
while(n > 0) {
System.out.println("tick " + n);
n--;
}
}
}
Output:
tick 5
tick 4
tick 3
tick 2
tick 1
Example
public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=5);
}
}
Output:
1
2
3
4
5
3.for loop
• For loop provides a concise way of writing the loop structure.
• A for statement consumes the initialization,
condition and increment/decrement in one line.
Syntax
for(initialization; condition; iteration) {
// body
}
Example
public class ForExample {
public static void main(String[] args) {
for(int i=1;i<=5;i++){
System.out.println(i);
}
}}
Output:
1
2
3
4
5
4.for-each Loop
• The for-each loop is used to traverse array or collection in java. It is easier to use than
simple for loop because we don't need to increment value and use subscript notation.
• It works on elements basis not index.
Example:
class ForEach {
public static void main(String args[]) {
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int x : nums) {
System.out.println("Value is: " + x);
sum += x;
}
System.out.println("Summation: " + sum);
}
}
Output:
Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 6
Value is: 7
Value is: 8
Value is: 9
Value is: 10
Summation: 55
5.Nested Loops
Java allows loops to be nested. That is, one loop may be inside another.
Example:
// Loops may be nested.
class Nested {
public static void main(String args[])
{
int i, j;
for(i=0; i<10; i++) {
for(j=i; j<10; j++)
System.out.print(".");
System.out.println();
}}
}
Output:
..........
.........
........
.......
......
.....
....
...
..
.
Sample Program:
Since Java is purely an Object Oriented Programming language, without creating anobject to
a class it is not possible to access methods and members of a class. Butmain method is also a
method inside a class, since program execution starts frommain method we need to call main
method without creating an object.
Escape Sequence:
Java supports all escape sequence which is supported by C/ C++. Acharacter preceded by a
backslash (\) is an escape sequence and has special meaningto the compiler.
When an escape sequence is encountered in a print statement, thecompiler interprets it
accordingly.
Once a class has been defined, we can create any number of objects belonging to that class
A class is thus a collection of objects similar types
For examples, guava, mango and orange are objects of the class fruit.
OBJECTS
e.g.:
Student s; // s is reference variable
s = new Student (); // allocate an object to reference variable s
The above two steps can be combined and rewritten in a single statement as:
Classname variable_name= new Classname ( ); // allocate an object
When a program is executed, the objects interact by sending messages to one another. For
example, if “customer” and “account” are to object in a program, then the customer object
may send a message to the count object requesting for the bank balance.
Each object contain data, and code to manipulate data. Objects can interact without having to
know details of each other’s data or code. It is sufficient to know the type of message
accepted, and the type of response returned by the objects.
A constructor may have or may not have parameters. Parameters are local
variables to receive data.
Example:
Program to initialize student details using default constructor and display the
same.
//Program to initialize student details using default constructor and displaying the same.
class Student
{
int rollNo;
String name;
Student ()
{
rollNo = 101;
name = "Suresh";
}
void display ()
{
System.out.println ("Student Roll Number is: " + rollNo);
System.out.println ("Student Name is: " + name);
}
}
class StudentDemo
{
public static void main(String args[])
{
Ex:2
class Box
{
double width;
double height;
double depth;
Box()
{
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
double volume()
{
return width * height * depth;
}
}
class BoxDemo6 {
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Output:
Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0
2.Parameterized (Argument)constructor
A constructor with one or more parameters is called parameterized constructor.
{
int rollNo;
String name;
o Default constructor is used to initialize every object with same data where
asparameterized constructor is used to initialize each object with different data.
o If no constructor is written in a class then java compiler will provide default values.
{ rollNo = r;
name = n;
void display ()
}
class StudentDemo
{
public static void main(String args[])
{
Student s1 = new Student(101, “Suresh”);
System.out.println (“s1 object contains: “ );
s1.display();
Student s2 = new Student (102, “Ramesh”);
Example:To copy the values of one object into another using java copy constructor.
COSTRUCTOR OVERLOADING
In Java, we can overload constructors like methods. The constructor overloading can be defined as
the concept of having more than one constructor with different parameters so that every constructor
can perform a different task.
Example:
Consider the following Java program, in which we have used different constructors in the class.
}
}
Program : Write a program to use „this‟ to refer the current class parameterized
constructor and current class instance variable.
//this demo
class Person
{
String name;
{
this (“Ravi Sekhar”); // calling present class parameterized constructor
this.display ( ); // calling present class method
}
{
this.name = name; // assigning present class variable with parameter “name”
}
void display( )
{
System.out.println ("Person Name is = " + name);
}
}
class ThisDemo
{
public static void main(String args[])
{
Person p = new Person ( );
}
}
Example:2
class Student
{
int id;
String name;
Student(int id, String name)
{
this.id = id;
this.name = name;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
stud1.display();
stud2.display();
}
}
Output:
01 Tarun
02 Barun
Java – Methods
A Java method is a collection of statements that are grouped together to perform an operation.
A method is a collection of statements that perform some specific task and return result to
the caller.
A method can perform some specific task without returning anything.
Methods are time savers and help us to reuse the code without retyping the code.
Methods allow us to reuse the code without retyping the code.
Method Declaration
In general, method declarations has six components :
1. Modifier-: Defines access type of the method i.e. from where it can be accessed in your
application. In Java, there 3 type of the access specifiers.
public: accessible in all class in your application.
protected: accessible within the class in which it is defined and in its subclass(es)
private: accessible only within the class in which it is defined.
2. The return type : The data type of the value returned by the method ,or void if does not
return a value.
3. Method Name : the rules for variable names apply to method names as well, but the
convention is a little different.
4. Parameter list : Comma separated list of the input parameters are defined, If there are no
parameters, you must use empty parentheses ().
5. Exception list : The exceptions you expect by the method can throw, you can specify these
exception(s).
Method body: it is enclosed between braces. The code you need to be executed to perform your
intended operations.
max(int x, int y)
Example:
class addexample
{
public static void main (String[] args)
{
// creating an instance of Addition class
Addition add = new Addition();
int s = add.addTwoInt(1,2);
System.out.println("Sum of two integer values :"+ s);
}
}
Output :
Overloading Methods
The Java programming language supports overloading methods, and Java can distinguish between
methods with different method signatures. This means that methods within a class can have the
same name if they have different parameter lists
In the Java programming language, you can use the same name for all the drawing methods
but pass a different argument list to each method.
Thus, the data drawing class might declare four methods named draw, each of which has a
different parameter list.
class OverloadDemo
{
void test()
{
System.out.println("No parameters");
}
void test(int a)
{
System.out.println("a: " + a);
}
void test(int a, int b)
{
System.out.println("a and b: " + a + " " + b);
}
double test(double a)
{
System.out.println("double a: " + a);
return a*a;
}
}
class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
double result;
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
Output:
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625
Method Overriding
• When a method in a subclass has the same name and type signature as a method in its
superclass, then the method in the subclass is said to override the method in the superclass.
• When an overridden method is called from within its subclass, it will always refer to the
version of that method defined by the subclass.
Example:
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
void show() {
System.out.println("i and j: " + i + " " + j);
EXAMPLE:
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data); //Compile Time Error
obj.msg(); //Compile Time Error
}
}
Role of Private Constructor
• If you make any class constructor private, you instance of that class from outside the class.
For example:
11.Static members
1.Static blocks
• If you need to do computation in order to initialize your static variables, you can declare a
static block that gets executed exactly once, when the class is first loaded.
Example:
class Test
{
static int a = 10;
static int b;
static {
System.out.println("Static block initialized.");
3.Static methods
• When a method is declared with static keyword, it is known as static method.
• When a member is declared static, it can be accessed before any objects of its class are
created, and without reference to any object.
• The most common example of a static method is main( ) method.
Methods declared as static have several restrictions:
• They can only directly call other static methods.
• They can only directly access static data.
• They cannot refer to this or super in any way.
Syntax:
1 /* text */
The compiler ignores everything from /* to */.
2 //text
The compiler ignores everything from // to the end of the line.
3 /** documentation */
This is a documentation comment and in general its called doc comment.
The JDK javadoc tool uses doc comments when preparing automatically
generated documentation.
Following is a simple example where the lines inside /*….*/ are Java multi-line comments.
Similarly, the line which preceeds // is Java single-line comment.
Example
/**
* <h1>Hello, World!</h1>
* The HelloWorld program implements an application that
* simply displays "Hello World!" to the standard output.
* <p>
* Giving proper comments in your program makes it more
* user friendly and it is assumed as a high quality code.
*/
public class HelloWorld
{
1.Comment Insertion
The javadoc utility extracts information for the following items:
1. Packages
2. Public classes and interfaces
3. Public and protected fields
4. Public and protected constructors and methods
i) Class Comments
The class comment must be placed after any import statements, directly before the class
definition.
ii) Method Comments
Each method comment must immediately precede the method that it describes. In addition to the
general-purpose tags, you can use the following tags:
• @param variable description
This tag adds an entry to the “parameters” section of the current method. The description can span
multiple lines and can use HTML tags. All @param tags for one method must be kept together.
• @return description
This tag adds a “returns” section to the current method. The description can span multiple lines and
can use HTML tags.
• @throws class description
iii) Field Comments
You only need to document public fields—generally that means static constants. For example:
/**
* The "Hearts" card suit
*/
public static final int HEARTS = 1;
iv) General Comments
The following tags can be used in class documentation comments:
• @author name
This tag makes an “author” entry. You can have multiple @author tags, one for each author.
• @version text
This tag makes a “version” entry. The text can be any description of the current version.
The following tags can be used in all documentation comments:
• @since text