0% found this document useful (0 votes)
26 views

Unit I Java

Uploaded by

vbharathi.se
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Unit I Java

Uploaded by

vbharathi.se
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

UNIT I JAVA INTRODUCTION 9

Review of object oriented programming - Objects and classes in Java – Defining classes –
Methods - Access specifiers – static members – static fields - static methods - static variables
– constructors -Default constructor - parameterized constructor – finalize method – Arrays –
Strings – Packages – user defined packages – Java Doc comments
Java Classes
A class in Java is a set of objects which shares common characteristics/ behavior and
common properties/ attributes. It is a user-defined blueprint or prototype from which
objects are created. For example, Student is a class while a particular student named Ravi is
an object.
Properties of Java Classes
1. Class is not a real-world entity. It is just a template or blueprint or prototype from
which objects are created.
2. Class does not occupy memory.
3. Class is a group of variables of different data types and a group of methods.
4. A Class in Java can contain:
• Data member
• Method
• Constructor
• Nested Class
• Interface
Class Declaration in Java
access_modifier class <class_name>
{
data member;
method;
constructor;
nested class;
interface;
}

Components of Java Classes


In general, class declarations can include these components, in order:
1. Modifiers: A class can be public or has default access (Refer this for details).
2. Class keyword: class keyword is used to create a class.
3. Class name: The name should begin with an initial letter (capitalized by convention).
4. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the
keyword extends. A class can only extend (subclass) one parent.
5. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if
any, preceded by the keyword implements. A class can implement more than one
interface.
6. Body: The class body is surrounded by braces, { }.

class Student {
int id;
String name;
public static void main(String args[])
{

Student s1 = new Student();


System.out.println(s1.id);
System.out.println(s1.name);
}
}

An object in Java is a basic unit of Object-Oriented Programming and represents real-life


entities. Objects are the instances of a class that are created to use the attributes and
methods of a class. A typical Java program creates many objects, which as you know,
interact by invoking methods. An object consists of :
1. State: It is represented by attributes of an object. It also reflects the properties of an
object.
2. Behavior: It is represented by the methods of an object. It also reflects the response of
an object with other objects.
3. Identity: It gives a unique name to an object and enables one object to interact with
other objects.

Initializing a Java object


The new operator instantiates a class by allocating memory for a new object and returning a
reference to that memory. The new operator also invokes the class constructor.

Syntax

Rectangle rect1; //declare

Rect1 = new rectangle(); //instantiate

(or)

Rectangle rect1 = new rectangle();

• We can create any number of objects for the rectangle class.


Eg:
Rectangle rect1 = new rectangle();
Rectangle rect2 = new rectangle();
• Each object has its own copy of the member variables of its class.
• Any changes to the variables of one object will not affect the variables of another
objects.
class Boy
{
String name;
String address;
int age;
void print()
{
System.out.println("Boy’s Details are:”);
};

public static void main(String[] args)


{
Boy obj = new Boy();
obj.name = "George";
obj.address = "Los Angels, USA";
obj.age = 23;
obj.print();
System.out.println("Name of the boy is: "+obj.name);
System.out.println("Address of the boy is: "+obj.address);
System.out.println("Age of the boy is: "+obj.age);
}
}
OUTPUT:
Boy’s Details are:
Name of the boy is: George
Address of the boy is: Los Angels, USA
Age of the boy is: 23

Access Modifiers in Java


1. Private access modifier
2. Role of private constructor
3. Default access modifier
4. Protected access modifier
5. Public access modifier
6. Access Modifier with Method Overriding

There are two types of modifiers in Java: access modifiers and non-access modifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be accessed
from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.

There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access modifiers only.

1) Private

The private access modifier is accessible only within the class.

Simple example of private access modifier

In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class,
so there is a compile-time error.

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
}
}

2) Default

If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It provides
more accessibility than private. But, it is more restrictive than protected, and public.

Example of default access modifier

In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.

//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}

In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
3) Protected

The protected access modifier is accessible within package and outside the package but
through inheritance only.

The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.

It provides more accessibility than the default modifer.

Example of protected access modifier

In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this
package is declared as protected, so it can be accessed from outside the class only through
inheritance.

//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
import pack.*;

class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello

4) Public

The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.

Example of public access modifier

//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

//save by B.java

package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

static members – static fields - static methods - static variables:


The static keyword in Java is mainly used for memory management. The static keyword in
Java is used to share the same variable or method of a given class. The users can apply
static keywords with variables, methods, blocks, and nested classes. The static keyword
belongs to the class than an instance of the class. The static keyword is used for a constant
variable or a method that is the same for every instance of a class.
The static keyword is a non-access modifier in Java that is applicable for the
following:
1. Blocks
2. Variables
3. Methods
4. Classes

Characteristics of static keyword:

• Shared memory allocation: Static variables and methods are allocated memory space
only once during the execution of the program. This memory space is shared among all
instances of the class, which makes static members useful for maintaining global state
or shared functionality.
• Accessible without object instantiation: Static members can be accessed without the
need to create an instance of the class. This makes them useful for providing utility
functions and constants that can be used across the entire program.
• Associated with class, not objects: Static members are associated with the class, not
with individual objects. This means that changes to a static member are reflected in all
instances of the class, and that you can access static members using the class name
rather than an object reference.
• Cannot access non-static members: Static methods and variables cannot access non-
static members of a class, as they are not associated with any particular instance of the
class.
• Can be overloaded, but not overridden: Static methods can be overloaded, which
means that you can define multiple methods with the same name but different
parameters. However, they cannot be overridden, as they are associated with the class
rather than with a particular instance of the class.
When a member is declared static, it can be accessed before any objects of its class are
created, and without reference to any object. For example, in the below java program, we
are accessing static method m1() without creating any object of the Test class.

class Test
{
// static method
static void m1()
{
System.out.println("from m1");
}

public static void main(String[] args)


{
// calling m1 without creating
// any object of class Test
m1();
}
}

Output
from m1

Static blocks
If you need to do the 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.
Consider the following java program demonstrating the use of static blocks.

class Test
{
// static variable
static int a = 10;
static int b;

// static block
static {
System.out.println("Static block initialized.");
b = a * 4;
}

public static void main(String[] args)


{
System.out.println("from main");
System.out.println("Value of a : "+a);
System.out.println("Value of b : "+b);
}
}

Output
Static block initialized.
from main
Value of a : 10
Value of b : 40

Static variables

When a variable is declared as static, then a single copy of the variable is created and
shared among all objects at the class level. Static variables are, essentially, global variables.
All instances of the class share the same static variable.
Important points for static variables:
• We can create static variables at the class level only.
• static block and static variables are executed in the order they are present in a program

class Test
{
// static variable
static int a = m1();

// static block
static {
System.out.println("Inside static block");
}

// static method
static int m1() {
System.out.println("from m1");
return 20;
}

// static method(main !!)


public static void main(String[] args)
{
System.out.println("Value of a : "+a);
System.out.println("from main");
}
}

Output
from m1
Inside static block
Value of a : 20
from main

Static methods

When a method is declared with the static keyword, it is known as the static method. The
most common example of a static method is the main( ) method. As discussed above, Any
static member can be accessed before any objects of its class are created, and without
reference to any object. 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

class Student{
int rollno;
String name;
static String college = "ITS";
//static method to change the value of static variable
static void change(){
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}
//method to display values
void display(){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to create and display the values of object
public class TestStaticMethod{
public static void main(String args[]){
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when an instance
of the class is created. At the time of calling constructor, memory for the object is allocated in
the memory.
It is a special type of method which is used to initialize the object. Every time an object is
created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class.
In such case, Java compiler provides a default constructor by default.
There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.
Note: It is called constructor because it constructs the values at the time of object creation. It
is not necessary to write a constructor for a class. It is because java compiler creates a default
constructor if your class doesn't have any.
Characteristics of a constructor:
• It has the same name as the class.
• A class can have more than one constructor.
• It can take zero, one or more parameters.
• It has no return value.
• It can be overloaded.
• It is always called with new operator.
Functions of a constructor:
• It can be used to initialize the fields.
• It allocates memory space too the fields
Rules for creating Java constructor
There are two rules defned for the constructor.
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, fnal, and synchronized
Types of Java constructors
There are two types of constructors in Java:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
Java Default Constructor
A constructor is called "Default Constructor" when it doesn't have any
parameter.
Syntax of default constructor:
[access-specifier] class name (arguments)
{
Statements;
}
Example of default constructor

E.G.: Constructor

import java.io.*;

class add

int a=0;

int b=0;

int c;

add(int n1,int n2)


{

System.out.println("Parameterized constructor");

a=n1;

b=n2;

add()

System.out.println("Default constructor");

void addnum()

c=a+b;

void print()

System.out.println("value of A="+a);

System.out.println("value of B="+b);

System.out.println("Sum="+c);

class add1{

public static void main(String args[]){

add A=new add(10,20);

A.addnum();

A.print();
add B=new add();

finalize() Method

Finalize() is the method of Object class. This method is called just before an object is garbage
collected. finalize() method overrides to dispose system resources, perform clean-up activities
and minimize memory leaks.

Syntax

1. protected void finalize() throws Throwable

Throw

Throwable - the Exception is raised by this method

Example 1:

public class JavafinalizeExample1 {


public static void main(String[] args)
{
JavafinalizeExample1 obj = new JavafinalizeExample1();
System.out.println(obj.hashCode());
obj = null;
// calling garbage collector
System.gc();
System.out.println("end of garbage collection");

}
@Override
protected void finalize()
{
System.out.println("finalize method called");
}
}

Output:

2018699554
end of garbage collection
finalize method called

Arrays in Java
Array in Java is a group of like-typed variables referred to by a common name.
• In Java, all arrays are dynamically allocated.
• Arrays may be stored in contiguous memory [consecutive memory locations].
• Since arrays are objects in Java, we can find their length using the object
property length. This is different from C/C++, where we find length using sizeof.
• A Java array variable can also be declared like other variables with [] after the data
type.
• The variables in the array are ordered, and each has an index beginning with 0.
• Java array can also be used as a static field, a local variable, or a method parameter.
• The size of an array must be specified by int or short value and not long.
• The direct superclass of an array type is Object.
• Every array type implements the interfaces Cloneable and java.io.Serializable.
• This storage of arrays helps us randomly access the elements of an array [Support
Random Access].
• The size of the array cannot be altered(once initialized). However, an array reference
can be made to point to another array.

The actual objects are stored in a heap segment.


Creating, initializing, and accessing an Array

One-Dimensional Arrays:

The general form of a one-dimensional array declaration is

datatype var-name[];
OR
datatype[] var-name;

class GFG {
public static void main(String[] args)
{
// declares an Array of integers.
int[] arr;

// allocating memory for 5 integers.


arr = new int[5];

// initialize the first elements of the array


arr[0] = 10;

// initialize the second elements of the array


arr[1] = 20;

// so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;

// accessing the elements of the specified array


for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i
+ " : " + arr[i]);
}
}

Output
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50

Multidimensional Array Declaration

int[][] intArray = new int[10][20]; //a 2D array or matrix


int[][][] intArray = new int[10][20][10]; //a 3D array

Example of Muilti Dimensional Array

public class multiDimensional {


public static void main(String args[])
{
// declaring and initializing 2D array
int arr[][]
= { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } };

// printing 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
System.out.print(arr[i][j] + " ");

System.out.println();
}
}
}

Output
279
361
742

Passing Arrays to Methods


Like variables, we can also pass arrays to methods. For example, the below program passes
the array to method sum to calculate the sum of the array’s values.
• Java

public class Test {


public static void main(String args[])
{
int arr[] = { 3, 1, 2, 5, 4 };

sum(arr);
}

public static void sum(int[] arr)


{
// getting sum of array values
int sum = 0;

for (int i = 0; i < arr.length; i++)


sum += arr[i];

System.out.println("sum of array values : " + sum);


}
}

Output
sum of array values : 15

Strings
In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:

char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);

is same as:

String s="Hello";

Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring()
etc.

The java.lang.String class


implements Serializable, Comparable and CharSequence interfaces.

What is String in Java?

Generally, String is a sequence of characters. But in Java, string is an object that represents a
sequence of characters. The java.lang.String class is used to create a string object.
How to create a string object?

There are two ways to create String object:

1. By string literal
2. By new keyword

1) String Literal

Java String literal is created by using double quotes. For Example:

String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance

2) By new keyword

1. String s=new String("Welcome");//creates two objects and one reference variable

Java String Example

public class StringExample{


public static void main(String args[]){
String s1="java";//creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}

Output:

java
strings
example

Java String class methods

By Using equals() Method


The String class equals() method compares the original content of the string. It compares values
of string for equality. String class provides the following two methods:

class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
} OUTPUT:
true
true
false

String compare by compareTo() method

The String class compareTo() method compares values lexicographically and returns an integer
value that describes if first string is less than, equal to or greater than second string.

Suppose s1 and s2 are two String objects. If:

o s1 == s2 : The method returns 0.


o s1 > s2 : The method returns a positive value.
o s1 < s2 : The method returns a negative value.

class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}
Output:

0
1
-1

String Concatenation by concat() method

The String concat() method concatenates the specified string to the end of current string.
Syntax:

public String concat(String another)

class TestStringConcatenation3{
public static void main(String args[]){
String s1="Sachin ";
String s2="Tendulkar";
String s3=s1.concat(s2);
System.out.println(s3);//Sachin Tendulkar
}
}

Output:
Sachin Tendulkar

Substring() method

A part of String is called substring. In other words, substring is a subset of another String.
Java String class provides the built-in substring() method that extract a substring from the
given string by using the index values passed as an argument. In case of substring() method
startIndex is inclusive and endIndex is exclusive.

o startIndex: inclusive
o endIndex: exclusive

1. String s="hello";
2. System.out.println(s.substring(0,2)); //returns he as a substring

In the above substring, 0 points the first letter and 2 points the second letter i.e., e (because end
index is exclusive).
public class TestSubstring{
public static void main(String args[]){
String s="SachinTendulkar";
System.out.println("Original String: " + s);
System.out.println("Substring starting from index 6: " +s.substring(6));//Tendulkar
System.out.println("Substring starting from index 0 to 6: "+s.substring(0,6)); //Sachin
}
} Output:
Original String: SachinTendulkar
Substring starting from index 6: Tendulkar
Substring starting from index 0 to 6: Sachin

Java String toUpperCase() and toLowerCase() method

The Java String toUpperCase() method converts this String into uppercase letter and String
toLowerCase() method into lowercase letter.

public class Stringoperation1


{
public static void main(String ar[])
{
String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s);//Sachin(no change in original)
}
}

Output:

SACHIN
sachin
Sachin

Packages
A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Types of packages:

Built-in Packages
These packages consist of a large number of classes which are a part of Java API.Some of
the commonly used built-in packages are:
1) java.lang: Contains language support classes(e.g classed which defines primitive data
types, math operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user
interfaces (like button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.
User-defined packages
These are the packages that are defined by the user.

Simple example of java package

The package keyword is used to create a package in java.

//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Output:Welcome to package

How to access package from another package?

There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.

1) Using packagename.*

If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.

The import keyword is used to make the classes and interface of another package accessible to
the current package.

Example of package that import the packagename.*

//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

2) Using packagename.classname

If you import package.classname then only declared class of this package will be accessible.

Example of package by import package.classname

//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

3) Using fully qualified name

If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.

It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.

Example of package by import fully qualified name

//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello

Java DOC Comments(Java - Documentation Comments)


The Java comments are the statements in a program that are not executed by the compiler and
interpreter.

Why do we use comments in a code?

o Comments are used to make the program more readable by adding the details of the
code.
o It makes easy to maintain the code and to find the errors easily.
o The comments can be used to provide information or explanation about the variable,
method, class, or any statement.
o It can also be used to prevent the execution of program code while testing the alternative
code.

Types of Java Comments

There are three types of comments in Java.

1. Single Line Comment


2. Multi Line Comment
3. Documentation Comment

1) Java Single Line Comment


The single-line comment is used to comment only one line of the code. It is the widely used
and easiest way of commenting the statements.

Single line comments starts with two forward slashes (//). Any text in front of // is not executed
by Java.

Syntax:

//This is single line comment

public class CommentExample1 {


public static void main(String[] args) {
int i=10; // i is a variable with value 10
System.out.println(i); //printing the variable i
}
}

Output:

10

2)Java Multi Line Comment

The multi-line comment is used to comment multiple lines of code. It can be used to explain a
complex code snippet or to comment multiple lines of code at a time (as it will be difficult to
use single-line comments there).

Multi-line comments are placed between /* and */. Any text between /* and */ is not executed
by Java.

Syntax:

/*
This
is
multi line
comment
*/

public class CommentExample2 {


public static void main(String[] args) {
/* Let's declare and
print variable in java. */
int i=10;
System.out.println(i);
/* float j = 5.9;
float k = 4.4;
System.out.println( j + k ); */
}
}
Output:
10

3) Java Documentation Comment

Documentation comments are usually used to write large programs for a project or software
application as it helps to create documentation API. These APIs are needed for reference, i.e.,
which classes, methods, arguments, etc., are used in the code.

To create documentation API, we need to use the javadoc tool. The documentation comments
are placed between /** and */.

Syntax:

/**
*
*We can use various tags to depict the parameter
*or heading or author name
*We can also use HTML tags
*
*/

javadoc tags

Some of the commonly used tags in documentation comments:

Tag Syntax Description

{@docRoot} {@docRoot} to depict relative path to root directory of


generated document from any page.
@author @author name - text To add the author of the class.

@code {@code text} To show the text in code font without


interpreting it as html markup or nested javadoc
tag.

@version @version version-text To specify "Version" subheading and version-


text when -version option is used.

@since @since release To add "Since" heading with since text to


generated documentation.

@param @param parameter- To add a parameter with given name and


name description description to 'Parameters' section.

@return @return description Required for every method that returns


something (except void)

Let's use the Javadoc tag in a Java program.

Calculate.java

import java.io.*;

/**
* <h2> Calculation of numbers </h2>
* This program implements an application
* to perform operation such as addition of numbers
* and print the result
* <p>
* <b>Note:</b> Comments make the code readable and
* easy to understand.
*
* @author Anurati
* @version 16.0
* @since 2021-07-06
*/

public class Calculate{


/**
* This method calculates the summation of two integers.
* @param input1 This is the first parameter to sum() method
* @param input2 This is the second parameter to the sum() method.
* @return int This returns the addition of input1 and input2
*/
public int sum(int input1, int input2){
return input1 + input2;
}
/**
* This is the main method uses of sum() method.
* @param args Unused
* @see IOException
*/
public static void main(String[] args) {
Calculate obj = new Calculate();
int result = obj.sum(40, 20);

System.out.println("Addition of numbers: " + result);


}
}

Compile it by javac tool:

Create Document

Create documentation API by javadoc tool:


Are Java comments executable?

Java comments are not executed by the compiler or interpreter, however, before the lexical
transformation of code in compiler, contents of the code are encoded into ASCII in order to
make the processing easy.

You might also like