Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
11 views63 pages

Unit - I Introduction To Oop and Java

The document provides an introduction to Object-Oriented Programming (OOP) and Java, detailing key concepts such as classes, objects, encapsulation, abstraction, inheritance, polymorphism, and dynamic binding. It outlines the features and benefits of OOP, Java buzzwords, and basic Java terminologies including bytecode, JDK, JRE, and JVM. Additionally, it explains the structure of a Java program, including documentation, package, import, and main method sections, along with Java tokens and their types.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views63 pages

Unit - I Introduction To Oop and Java

The document provides an introduction to Object-Oriented Programming (OOP) and Java, detailing key concepts such as classes, objects, encapsulation, abstraction, inheritance, polymorphism, and dynamic binding. It outlines the features and benefits of OOP, Java buzzwords, and basic Java terminologies including bytecode, JDK, JRE, and JVM. Additionally, it explains the structure of a Java program, including documentation, package, import, and main method sections, along with Java tokens and their types.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

UNIT - I INTRODUCTION TO OOP AND JAVA

Overview of OOP:

OOP - Object Oriented Programming​


OOP is a programming paradigm based on the concepts of “objects”, which may contain data in the form of
fields (often known as attributes) and code in the form of procedures (often known as methods or functions).​
Object = Data + Function

E.g.: C++, Python, C#, Java, Beta, IDL Script, COBOL, etc.

Features of OOP / Concepts of OOP / Characteristics of OOP:


●​ Class
●​ Object
●​ Encapsulation
●​ Abstraction
●​ Inheritance
●​ Polymorphism
●​ Message Passing
●​ Dynamic binding
Class:
Class is a user-defined data type.A class can be defined as an entity in which data and functions are put
together. A class is a collection of properties.​
→ Data, Methods​
Class

| Data |

|------|

|Methods|

Eg: Real-Time​
Car – collection of properties.​
Steering, Clutch, Brake, Window, Mirrors, Seat, etc.​
Eg2:

Student → Class​
Anitha, Anu → Object​
Department – Class​
CSE, IT, CIVIL – Object​

Syntax:​
class name_of_class​
{​
private:​
​ variable declaration; // variable​
​ function declaration;​
public:​
​ variable declaration; // methods​
​ function declaration; // read, write, play​
};​
Object:​
- Object is the instance of a class.​
- Object is used to invoke the members of the class (properties/tasks to be performed).​
- Object has states and behaviours.​
Example: car → key​
- States: colour, name, model​
- Behaviors: key
class_name object_name = new class_name;
(or) class_name
object_name;
object_name = new class_name();

Encapsulation:​
The wrapping up of data and methods into a single unit (Class) is known as encapsulation.​
Concept:​
Encapsulation leads to the concept of data hiding, which means data is prevented from external access.​
Example: Consider the capsule. (Method + Variable inside Class)

Abstraction:​
The process of stating the essential things without including the background details is known as abstraction.​
Eg:​
- pow() → Header file​
- Accelerator and Brake
For Example: - Consider an ATM Machine; All are performing operations on the ATM machine like cash
withdrawal, money transfer, retrieve mini- statement…etc. but we can't know internal details about ATM.
Abstraction provides advantage of code reuse.
Abstraction enables program open for extension.
In java, abstract classes and interfaces are used to achieve Abstraction.

Inheritance:​
Inheritance is the process of creating a new class from an existing class.The idea behind inheritance in Java is
that we can create new classes that are built upon existing classes. When we inherit from an existing class, we
can reuse methods and fields of the parent class, and we can add new methods and fields also. Inheritance
represents the IS-A relationship, also known as the parent-child relationship. For example:- In a child and
parent relationship, all the properties of a father are inherited by his son.
A → Base class / Father class​
B → Derived class / Child class

Syntax of Java Inheritance

class Subclass-name extends Superclass-name{

//methods and fields


}
Concepts:​
- Reusability​
- Derived class without modifying (rewriting) it.​
Types of Inheritance:​
1. Single-level inheritance​
2. Multi-level inheritance​
3. Multiple inheritance​
4. Hierarchical inheritance​
5. Hybrid inheritance​
Message Passing:​
- Message passing is the sending and receiving of information by the object.​
- Establishing communication among objects.


Example:
Employee.getName(name);
Where,
Employee – object name
getName – method name (message) name - information​
Polymorphism:​
- Polymorphism means it can take more than one form. Polymorphism is a concept by which we can perform a sing
action in different ways. An object can take more than one form.
●​ The word "poly" means many, and "morphs" means forms. So, polymorphism
means many forms.
●​ An operation may exhibit different behaviours in different instances. The
behaviour depends on the data types used in the operation.
●​ For Example:- Suppose if you are in a classroom that time you behave like a
student, when you are in the market that time you behave like a customer, when
you are at your home that time you behave like a son or daughter. Here, one
person presents in different-different behaviours.
Eg:​
class Shape {​
draw(); // one method (draw) with different properties​
}​

Subclasses:​
- Circle → draw()​
- Square → draw()​
- Rectangle → draw()​

Dynamic Binding:​
- Binding means linking of a procedure call to the code to be executed.​
- When the linking is done at runtime.​
- Object type is determined at runtime.


Comparison Table: Inheritance vs Polymorphism:

S.No Inheritance Polymorphism

1. The derived class can derive the properties and Polymorphism is the ability for an
methods of the base class. object to use different forms.

2. Types: single, multilevel, multiple, hybrid, Types: Run time, Compile time​
hierarchical inheritance. Overloading Types:​
1. Function overloading​
2. Operator overloading

Difference Between Encapsulation and Abstraction:

S.No Data Encapsulation Data Abstraction

1. Wrapping up the data and methods. Properties are highlighted.

2. Depends upon the object data type. Depends upon the independent object

3. Used in the software implementation phase. Software design phase.

4. Represented by inheritance. Represented by abstract classes.


Difference Between Class and Object:

S.No Class Object

1. A single class can be any no. of objects. Many objects can be created from one
class.

2. Class is persistent throughout the program. Created and destroyed as objects.

3. Class cannot be initialised with some Assign some property value to the
property value. objects.

4. Unique name Different names can be created.

Benefits of OOP:​
1. Inheritance → Redundant code eliminated.​
2. Modules → Communicate with each other (task).​
3. Data hiding → Unauthorised access.​
4. Multiple objects.​
5. Message passing technique → Communicate to external.​
6. Partitioning the code → Understanding.​

1.4 Java Buzzwords

The following are the features of the Java language:

1.​ Object Oriented


2.​ Simple
3.​ Secure
4.​ Platform Independent
5.​ Robust
6.​ Portable
7.​ Architecture Neutral
8.​ Dynamic
9.​ Interpreted
10.​High Performance
11.​ Multithreaded
12.​ Distributed

Simple:-​
✳ Java is very easy to learn.​
✳ Syntax is based on C++. So easy to learn.​
✳ Java has removed complicated features such as pointers.​
✳ Automatic Garbage collection is available in java.

Object Oriented:-​
✳ Java supports object-oriented concepts such as classes, objects, Abstraction, Encapsulation, inheritance
and polymorphism.​
✳ OO means we organise our SLW as a combination of different types of object. (data and behavior)
C++ ( can be without class) Java – No programs without classes and objects

With Class: With class:


#include<iostream.h> class import java.io.*; class Hello
display { {
public static void main(String args[])
public: {
System.out.println(“Hello!”);
void disp()
}
{
}
cout<<”Hello!”;
}
}; Without class is not possible
main()
{
display d; d.disp();

Without class: #include<iostream.h> void main()

{
clrscr();
cout<<”\n Hello!”; getch();
}

Platform Independent :​
✳ Java is a software-based platform-independent. (byte code)​
✳ Java compiler converts source file into byte code.​
✳ Bytecode is a platform-independent code because it can be run on multiple platforms such as Windows,
Linux, mac etc.​
(Write Once and Run Anywhere).​
✳ Two Components :​
1) Runtime Environment.​
2) API (Application Programming Interfaces).

Interpreted: Executes line by line​


Text Editor ➝ source code ➝ Java compiler​
↓​
JVM ← byte code​
↓​
operating system

Secured :​
(Java is secured because java programs run inside JVM.)

Robust : (strong)​
✳ Java uses strong mly management.​
✳ Java supports exception handling and types of checking mechanism.​
E.g.: my effective allocation​
int a[10] ➝ allocate 11​
java int a[5] ➝ only 1 - 5

✳ Type checking :​
int a;​
a = 10 + 5.5 ;

Architecture neutral :-​


✳ In C ➝ int : 2 bytes ➝ 32 bit architecture.​
4 bytes ➝ 64 "​
✳ In J ➝ int : 4 bytes of m/y for both 32 and 64 bit architecture​
✳ Java is architecture neutral.​
✳ Eg : Size of primitive data types is fixed.​
✳ Both Compilation and Interpretation .​
✳ JVM will interpret the bytecode into machine code and then execute it.

High performance :-​


✳ Java is an interpreted language.​
✳ so it will slower than compiled language like c or c++ .​
✳ But java enables high performance with the use of JIT.​
(Just - in - time) compiler (run)​
✳ JIT compiler is enabled by default.

Multithreaded :-​
✳ A thread is like a separate programs.​
✳ Multithread contains multiple programs and executing concurrently

Advantages :​
1) Doesn’t occupy mly for each thread.​
2) Share a common memory area.​
3) Multithread are important for web applications, multimedia etc..,

Distributed :​
✳ Java is distributed because it enables users to create distributed applications in java.​
✳ RMI ➝ Remote Method Invocation and EJB (Enterprise Java Beans) are used for creating distributed
applications.

Dynamic :​
✳ Java is a dynamic language.​
(classes on demand)​
✳ Supports dynamic loading of classes.​
✳ Supports functions from its native languages (C, C++)

3) Overview of Java

The Java programming language was originally developed by Sun Microsystems which was initiated by
James Gosling and released in 1995 as a core component of Sun Microsystems' Java platform (Java 1.0
[J2SE]).
BASIC JAVA TERMINOLOGIES:
1. BYTECODE:

Byte code is an intermediate code generated from the source code by java compiler and it is
platform independent.
2. JAVA DEVELOPMENT KIT (JDK):

●​ The Java Development Kit (JDK) is a software development environment usedfor


developing Java applications and applets.
●​ It includes the Java Runtime Environment (JRE), an interpreter/loader (java), a
compiler (javac), an archiver (jar), a documentation generator (javadoc) and other tools
needed in Java development.
3. JAVA RUNTIME ENVIRONMENT (JRE):

JRE is used to provide runtime environment for JVM. It contains set of libraries
+other files that JVM uses at runtime.
4. JAVA VIRTUAL MACHINE (JVM):
JVM is an interpreter that converts a program in Java bytecode (intermediate language) into native machine code
and executes it. JVM needs to be implemented for each platform because it will differ from platform to platform.

Structure of Java :

A Java source file is a plain text file containing Java source .java code and having extension. The .java
extension means that the file is a Java source file. A Java source code file contains source code for a
class, interface, enumeration, or annotation type. There are some rules associated to Java source
files.Java program may contain many classes of which only one class defines the main method.A Java
program may contain one or more sections.

1.​ Documentation Section​

2.​ Package Statements Section​

3.​ Import statements section​

4.​ Class Definition​

5.​ Main Method Class

Documentation Section:
1.​ Provides the information about the source program.

2.​ Section contains information which is not compiled by Java.​


Types: Single line comments (//), Multiline comments (/* ... */)

3.​ Written as comments

4.​ Comments are used for understanding the program.​


Package Section:

1.​ Using the keyword package.​

2.​ It is necessary to write the package statement in beginning.​

3.​ Group of classes, interfaces and other packages.

Import Section:

●​ An interface is similar to classes which consist of group of method declaration.


●​ Like classes, interfaces contain methods and variable.
●​ To link the interface to our program, the keyword implements is used.
○​ public class xx extends Applet implements ActionListener where, xx
– class name (subclass of Applet)Applet – Base class name
ActionListener – interface Extends & implements - keywords
●​ It is used when we want to implement the feature of Multiple Inheritance in Java
●​ It is an optional declaration.

Main Method Class

Every Java Standalone program requires a main method as its starting point. A Simple Java
Program will contain only the main method class. It creates objects of various classes and uses
those objects for performing various operations.When the end of main is reached the program
terminates and the control transferred back to the Operating system.
Syntax for writing main:
public static void main(String arg[])
where,
public – It is an access specifier to control the visibility of class members. main() must be
declared as public, since it must be called by code outside of its class when the
program is started.
static – this keyword allows the main() method to be called without having to instantiate the
instance of the class.

void – this keyword tells the compiler that main() does not return any value.

main() – is the method called when a Java application begins.


String arg[] – arg is an string array which receives any command-line arguments present when the program is
executed.
Java Tokens:

The smallest individual units in a program are known as tokens. A Java program is a collection of
tokens, comments, and white spaces.​
Types of Tokens:

●​ Reserved Keywords
●​ Identifiers
●​ Literal
●​ Operators
●​ Separators

Reserved Keywords:
50 reserved keywords are defined in Java. Written in lowercase.

Examples:​
abstract, boolean, break, byte, case, catch, finally, char, class, continue, default, do, double, else,
extends, false, final, float, for, if, import, long, native, private, public, ...

Identifiers or Variables:

A variable can be used to store a value of any data type.​


Declaration:

specifier datatype variable1, variable2, ..., variable n;

Example:

int c;
private float a, b;
The declaration represents:

1.​ Variable name


2.​ Type of data
3.​ Scope of the variable (specifier)

Rules:

1.​ Identifiers can be written using alphabets, digits, underscores.

2.​ Should not contain any other special character.

3.​ Should not be a space within.

4.​ Not start with a digit.


5.​ Case-sensitive.
○​ Eg: int a; int A;
6.​ Identifiers can be of any length.
Literals:

●​ Contain values that appear directly in the program.​

●​ Literals are variables that store a sequence of characters for representing constant values.​
Example: int cost = 10;

1) Integer Literal:

Integral data types → byte, short, int, long

●​ Decimal literals (Base 10) → 0–9​

●​ Octal literals (Base 8) → 0–7​

●​ Hexadecimal literals (Base 16) → 0–9 (A–F)​

●​ Binary literals → 0,1 (0b or 0B)

2) Floating Point Literal:

●​ We can specify literals in only decimal form​

●​ Decimal → Base 10 (0–9)​

Example:

double d = 123.456;

3) Character Literal:
1. Single quote: A single character within the single quote​
Example:​
char ch = 'a', 'b';

Allowed range: 0 to 65535​


4) String Literal:
Any sequence of characters within double quotes​
Example:​
String s = "Hello";

5) Boolean Literal:
Only two values are allowed: true or false​
Example:​
boolean b = true;

Operators:

●​ Operators are the symbols used in the expression for evaluating them.​
Example:

int a = 10, b = 5;

int sum = a + b; // '+' is the operator, 'a' and 'b' are operands

Here, the + operator tells the program to add the values of a and b.

Separators:

●​ () : Parenthesis​

●​ {} : Curly Brackets​

●​ [] : Square Brackets​

●​ ; : Terminate the statement​

●​ , : Commas are used to separate the contents​

●​ . : Separate the package name from sub-packages​


Data Types:

Data types in Java are of different sizes and values that can be stored in a variable.

Categories:

1.​Primitive Data Types (int, char, short, byte, long, float, boolean, double)​

2.​Non-primitive Data Types (String, array, etc.)

Primitive data are only single values and have no special capabilities. Primitive data types are those
whose variables allow us to store only one value and never allow storing multiple values of the same
type. This is a data type whose variable can hold a maximum of one value at a time.

4 categories:
1.​ Integers
2.​ Floating point numbers
3.​ Characters
4.​ Boolean​

i.Integers:

●​ Java defines 4 integer types: byte, short, int and long.​

●​ All of these are signed, positive or negative values.​


Name Bits Range Eg

long 64 -2⁶³ to 2⁶³-1 long a, b, c;

int 32 -2³¹ to 2³¹-1 int a, b, c;

short 16 -32768 to 32767 short a, b;

byte 8 -128 to 127 byte a, b;

ii. Floating point numbers:


The floating-point types denote numbers with fractional parts. The two floating-point
types are shown below​
Types:​
Float → single precision​
Double → double precision

●​ It allows decimal and fractional values.

Name Width (Bits) Range

double 64 4.9e⁻³²⁴ to 1.8e⁺³⁰⁸

float 32 1.4e⁻⁰⁴⁵ to 3.4e⁺⁰³⁸

iii.Character:
●​ It is a set of character used to represent identifiers, literals, keyword, expression and statements.

●​ char is a keyword.

●​ char is a 16-bit and range is 0 to 65,536.

●​ Numerals: 0 to 9

●​ Alphabets: a to z and A to Z

●​ Special characters: + - * / % = < > () [] {} . \ ; : ? # etc.,​

Boolean:

●​ boolean data type represents one bit of information.


●​ There are only two possible values: true and false.
●​ This data type is used for simple flags that track true/false conditions.
●​ Default value is false.
●​ Example: boolean one = true
Non-primitive data types:

●​ It contain a memory address of variable.​

●​ Because the reference type won't store the variable value directly in mly.

Categories:

1.​ Strings​

2.​ Array​

3.​ Class

Strings:

●​ Strings are defined as an array of characters.


●​ Syntax: String stringName = "Sequence of string";
●​ Eg: String str = "CSE";

Array:

●​ Array is a collection of elements of similar data type stored in contiguous memory allocation.

Syntax:​
datatype[] arrayname;​
(or)​
datatype arrayname[];
Eg: int a[];​
char ch[];

Variables and Arrays:

Variables:

A variable is a name that holds a value while the Java program is executed.​
A variable is assigned a datatype. A variable is a name of a memory location.

Syntax: datatype variableName = value;​


Eg: int a = 10;

Variables in Java
●​ A variable is a named piece of memory used for storing data in a Java program.

●​ A variable is an identifier used for storing a data value.

●​ A variable may take different values at different times during the execution of the program,
unlike constant.The variable's type determines what values it can hold and what operations can
be performed on it.​
Syntax to Declare Variables

datatype identifier [= value] [, identifier [= value], ...];

Example of Variable Declaration

int average = 0, height, totalHeight;

Note: totalHeight is a corrected version of total height (whitespace not allowed in variable names).

Rules for Naming Variables

1.​ A variable name must begin with a letter and must be a sequence of letters or digits.​

2.​ Variable names must not begin with digits.​

3.​ Uppercase and lowercase letters are distinct.​

○​ Example: Total and total are two different variables.​

4.​ A variable name should not be a Java keyword.​

5.​ Whitespace is not allowed in variable names.​

6.​ Variable names can be of any length.​

7.​ Allowed characters: alphabets, digits, underscore _, and dollar sign $.

Initializing Variables

●​ After the declaration of a variable, it must be initialized using an assignment statement.​

●​ It is not possible to use the value of an uninitialized variable.​

Two Ways to Initialize a Variable:

1. Initialize after declaration:

int months;

months = 1;

2. Declare and initialize on the same line:

int months = 12;

Dynamic Initialization of Variables


Java allows variables to be initialized dynamically using any valid expression at the time the variable is
declared.

Example: Program to compute the remainder

class FindRemainder {

public static void main(String[] args) {

int num = 5, den = 2;

int rem = num % den;

System.out.println("Remainder is " + rem);

Output:

Remainder is 1

In the above program:

●​ num and den are initialized with constants.​

●​ rem is initialized dynamically using the modulo operation on num and den.

Types of variables:

1.​ Local variable​

2.​ Instance variable​

3.​ Class or static variable

Local Variables Instance Variable Class / Static Variables

Local variables Instance variables are declared Class variables also known as static
aredeclared in methods, in a class, but outside a method, variables are declared with the static
constructors, or blocks. a constructor or any block. keyword in a class, but outside a method,
constructor or a block.
There would only be one copy of each class
variable per class, regardless of how many
objects are created from it.
Instance variables are created
Local variables are created Static variables are created when the
when an object is created with the
when the method, program starts and destroyed when the
use of the keyword 'new' and
constructor or block is program stops.
destroyed when the object is
entered and the variable
destroyed.
will be destroyed once it
exits the method,
constructor or block.

Access modifiers cannot be Access modifiers can be used for Access modifiers can be used for class
used for local variables. instance variables. variables.

Local variables are visible The instance variables are


only within the declared visible for all methods,
method, constructor or constructors and blocks in the Visibility is similar to instance variables.
block. class.
Instance variables have default
There is no default value The default values are the same as instance
values. For numbers the default
for local variables so local variables.
value is 0, for Booleans it is
variables should be
false and for object references it
declared and an initial value
is null. Values can be assigned
shouldbe assigned before
during
the first use.
the declaration or within the
constructor.
Instance variables can be
accesseddirectly by calling the Static variables can be accessed by calling
variable name inside the class. with the class name.
Local variables can only be
However within static methods
access inside the declared ClassName.VariableName.
and different class should be
block.
called using the fully qualified
name as follows:

ObjectReference.VariableNa
me.

E.g.: Class variable

static int c = 30; // → Static variable


int a = 10; // → Instance variable
public static void main(String args[]) {
int b = 20;
System.out.println(c); // 30
System.out.println(b); // 20
variable obj = new variable();
System.out.println(obj.a); // 10
}
classname objectname = new constructor();
Arrays:

Array is a collection of elements of similar datatype stored in contiguous memory allocation.​


It is index based and the first element is stored at 0th index.

Syntax:

datatype[] arrayname;
or
datatype arrayname[];

Eg:

int[] a;
or
int a[];

Advantages of Array:

1.​ Cost Optimization → Multiple values can be stored under a common name.​

2.​ Random Access → Data at any location can be retrieved.

Disadvantages of Array:

Inefficient Memory usage:​


Array is static. It is not resizable at runtime based on no. of user's input.​
To overcome the limitation, Java introduced the Collection concept.

Types of Array:

1.​ One-dimensional array​

2.​ Two-dimensional array​

3.​ Multidimensional array


One-Dimensional Array:
Definition: A one-dimensional array is an array in which the elements are stored in one variable
name by using only one subscript.

Syntax:

datatype[] arrayname;
or
datatype arrayname[];

Eg:int[] a;

Instantiation of an Array:

●​ Array can be created using the new keyword.​

●​ To allocate memory for array elements, we must mention the array size.​

Syntax:

arrayname = new datatype[size];


or
datatype[] arrayname = new datatype[size];

Eg:

int[] a = new int[5];

Diagram:
Index: 0 1 2 3 4
Element: □ □ □ ■ □ → Element at index 3
Array length is 5

Initialize Array:

Syntax:
datatype[] arrayname = new datatype[] {list of values};
or
datatype[] arrayname = {list of values};

Example:

int[] a = new int[]{10, 11, 12};


or
int[] a = {10, 11, 12};
Accessing Array Elements:

●​ An array's elements can be accessed by using indices.​

●​ The index starts from 0 and ends at the array size - 1.

●​ Each element in an array can be accessed using a for loop.

Program: Storing and Sorting the Values of an Array


class Arraysort {
public static void main(String args[]) {
int a[] = {20, 30, 40, 10};
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);
a.sort();
System.out.println("Sorted Array");
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);
}
}

Output:

20
30
40
10
Sorted Array:
10
20
30
40

Two-Dimensional Array:

Array with two subscripts is known as two dimensional array.

Syntax:

datatype[][] arrayname;
or
datatype arrayname[][];

Eg: int[][] a;

or
int a[][];
Instantiation of an Array:

●​ Array can be created using the new keyword.​

●​ To allocate memory for array elements, we must mention the array size.​

Syntax:

arrayname = new datatype[row size][column size];


or
datatype[][] a = new int[5][5];
or
a = new int[5][5];

Initialize Array:

Syntax:

datatype[][] arrayname = new datatype[][] {list of values separated by comma};


or
datatype[][] arrayname = {list of values separated by comma};

Eg:

int[][] a = {12, 13, 14};


int[][] a = new int[][] {12, 13, 14};

Accessing Array Elements:

The array elements can be accessed by using indices.​


The index starts from 0 and ends at array size - 1.​
Each element in an array can be accessed using a for loop.

sql
CopyEdit
Table:
Column 1 | Column 2 | Column 3 | Column 4
Row 1 → a[0][0] | a[0][1] | a[0][2] | a[0][3]
Row 2 → a[1][0] | a[1][1] | a[1][2] | a[1][3]
Row 3 → a[2][0] | a[2][1] | a[2][2] | a[2][3]
Program: Matrix Addition
class MatrixAddition {
public static void main(String args[]) {
int a[][] = {{1, 3, 4}, {2, 4, 3}, {3, 4, 5}};
int b[][] = {{1, 3, 4}, {2, 4, 3}, {1, 2, 4}};
int c[][] = new int[3][3];

for (int i = 0; i < 3; i++) {


for (int j = 0; j < 3; j++) {
c[i][j] = a[i][j] + b[i][j];
}
}

for (int i = 0; i < 3; i++) {


for (int j = 0; j < 3; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}

Output:

CopyEdit
268
486
469
Operators:
An operator in Java is a symbol that is used to perform operations. Operators are used to manipulate
primitive data types. Java operators can be classified as unary, binary, or ternary—meaning they take
one, two, or three arguments, respectively.

Types of Operators in Java:

1.​ Arithmetic Operator


2.​ Relational Operator
3.​ Bitwise Operator
4.​ Logical Operator
5.​ Assignment Operators
6.​ Ternary Operators
7.​ Unary Operator

1.Arithmetic Operator:

Arithmetic operators are used in mathematical expressions.

Eg:int a = 10, b = 20;

Operator Description Example Output

+ Adds values A & B A+B 30

- Subtracts B from A A-B -10

* Multiplies values A & B A*B 200

/ Divides B by A B/A 2

% Modulus → Remainder B%A 0

Program:
class AdArithmetic {
public static void main(String args[]) {
int a = 20, b = 15;
System.out.println("Addition \t" + (a + b));
System.out.println("Subtraction \t" + (a - b));
System.out.println("Multiplication \t" + (a * b));
System.out.println("Division \t" + (a / b));
System.out.println("Modulus \t" + (a % b));
}
}
Output:

mathematica
CopyEdit
Addition 35
Subtraction 5
Multiplication 300
Division 1
Modulus 5

2.Relational Operators

Relational operators in Java are used to compare 2 or more objects. Java provides sixrelational
operators: Assume variable A holds 10 and variable B holds 20, then:

Operator Description Example

== Checks if the values of two operands are equal. If yes, then the (A == B) is not true.
condition becomes true.

!= Checks if the values of two operands are not equal. If they are (A != B) is true.
not equal, then the condition becomes true.

> Checks if the value of the left operand is greater than the value of (A > B) is not true.
the right operand. If yes, then the condition becomes true.

< Checks if the value of the left operand is less than the value of (A < B) is true.
the right operand. If yes, then the condition becomes true.

Example:

public RelationalOperatorsDemo( )

int x = 10, y = 5; System.out.println("x > y : "+(x > y));

System.out.println("x < y : "+(x < y)); System.out.println("x >= y : "+(x >= y)); System.out.println("x
<= y : "+(x <= y)); System.out.println("x == y : "+(x == y)); System.out.println("x != y : "+(x != y));

public static void main(String args[])

new RelationalOperatorsDemo();
}

Output:

$java RelationalOperatorsDemo

x > y : true x < y : false x >= y : true

x <= y : false x == y : false x != y : true

3.Bitwise Operators

Java provides Bit wise operators to manipulate the contents of variables at the bit level. The result of
applying bitwise operators between two corresponding bits in the :operandsis shown in the Table below.

A​ B​ ~A​ A & B​A | B​ A ^ B

1​ 1​ 0​ 1​ 1​ 0

1​ 0​ 0​ 0​ 1​ 1

0​ 1​ 1​ 0​ 1​ 1

0​ 0​ 1​ 0​ 0​ 0

EXAMPLE:

public class Test

public static void main(String args[])

int a = 60; /* 60 = 0011 1100 */

int b = 13;​ /* 13 = 0000 1101 */int c = 0; c = a & b;​ /* 12 = 0000 1100 */ System.out.println("a
& b = " + c );

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;​ /*-61 = 1100 0011 */ System.out.println("~a = " + c
);

c = a << 2;​ /* 240 = 1111 0000 */

System.out.println("a << 2 = " + c ); c = a >> 2;​ /* 215 = 1111 */ System.out.println("a >> 2 = " + c
); c = a >>> 2;​​ /* 215 = 0000 1111 */

System.out.println("a >>> 2 = " + c );

}
}

Output:

$java Test

a & b = 12 a | b = 61 a ^ b = 49

~a = -61

a << 2 = 240

a >> 2​ = 15

a >>> 2 = 15

4. Logical Operators

Logical operators return a true or false value based on the state of the Variables. Given that x and y
represent boolean expressions, the boolean logical operators are defined in the Table below.

x&y x|y
x y !x x^y
x && y x || y
true true false true true False
true false false false true
true

false true false true


true true

false false false false


true false

Example:

public class LogicalOperatorsDemo

public LogicalOperatorsDemo()

boolean x = true; boolean y = false;

System.out.println("x & y : " + (x & y)); System.out.println("x && y : " + (x && y));
System.out.println("x | y : " + (x | y)); System.out.println("x || y: " + (x || y)); System.out.println("x ^ y :
" + (x ^ y));

System.out.println("!x : " + (!x));

}
public static void main(String args[])

new LogicalOperatorsDemo();

Output:

$java LogicalOperatorsDemo

x & y : false x && y : false x | y : true

x || y: true x ^ y : true

!x : false

5.Java Assignment Operator

The java assignment operator statement has the following

syntax:<variable> = <expression>

If the value already exists in the variable, it is overwritten by the assignment operator (=).

Example:

class OperatorExample {

public static void main(String args[]) {

int a = 10;

int b = 20;

a += 4; // a = a + 4 → a = 10 + 4 → 14

b -= 4; // b = b - 4 → b = 20 - 4 → 16

System.out.println(a); // 14

System.out.println(b); // 16

OUTPUT
14
16
6. Ternary Operator in Java (?:)

The ternary operator is a conditional operator that evaluates a boolean expression and returns one of
two values depending on whether the expression is true or false.​
It is called ternary because it takes three operands:

1.​ Condition (a boolean expression)


2.​ Value if true
3.​ Value if false

Syntax

variable = (condition) ? value_if_true : value_if_false;

●​ condition → any expression that results in a boolean value (true or false)​

●​ value_if_true → returned if the condition is true​

●​ value_if_false → returned if the condition is false

Flow

1.​ Evaluate the condition.


2.​ If the condition is true, return value_if_true.
3.​ If the condition is false, return value_if_false.

Example — Finding Minimum Value

class TernaryExample {

public static void main(String[] args) {

int a = 10, b = 20;

int min = (a < b) ? a : b; // Checks if a is less than b

System.out.println("Minimum value: " + min);

Output:

Minimum value: 10
7.Java Unary Operator
The Java unary operators require only one operand. Unary operators are used to perform various
operations
i.e.:
o Incrementing/decrementing a value by one
o Negating an expression
o Inverting the value of a boolean

Java Unary Operator Example: ++ and –


class OperatorExample {

public static void main(String args[]) {

int x = 10;

System.out.println(x++); // 10 (then x becomes 11)

System.out.println(++x); // 12

System.out.println(x--); // 12 (then x becomes 11)

System.out.println(--x); // 10

OUTPUT:

10
12
12
10
CONTROL-FLOW STATEMENTS
Java Control statements control the order of execution in a java program, based on data values
and conditional logic.

There are three main categories of control flow statements;

· Selection statements: if, if-else and switch.

· Loop statements: while, do-while and for.

· Transfer statements: break, continue, return, try-catch-finally and assert.

1.Selection Statements​
We use control statements when we want to change the default sequential order of execution

There are two types of decision making statements in Java. They are:

· if statements

· if-else statements

· nested if statements

· if-else if-else statements

· switch statements

1.If Statement:

An if statement consists of a Boolean expression followed by one or more statements.Block of statement


is executed when the condition is true otherwise no statement will beexecuted.

Syntax:

if(<conditional expression>)

< Statement Action>

If the Boolean expression evaluates to true then the block of code inside the if statement will be
executed.If not the first set of code after the end of the if statement (after the closingcurly brace) will be
executed.

Flowchart:
Example:

public class IfStatementDemo {

public static void main(String[] args)

int a = 10, b = 20; if (a > b)

System.out.println("a > b"); if (a < b)

System.out.println("b > a");

Output:

$java IfStatementDemo b > a

2.if-else Statement:

The if/else statement is an extension of the if statement. If the statements in the if statement fails, the
statements in the else block are executed.

Syntax:
The if-else statement has the following syntax:
if(<conditional expression>)
{
< Statement Action1>
}
else
{
< Statement Action2>
}
Example:

public class IfElseStatementDemo {

public static void main(String[] args)

int a = 10, b = 20; if (a > b) {

System.out.println("a > b");

else {

System.out.println("b > a");

Output:

$java IfElseStatementDemo b > a

3. Nested if Statement:

Nested if-else statements, is that using one if or else if statement inside another if or else ifstatement(s).

Syntax:

if(condition1)

if(condition2)
{

//Executes this block if condition is True

else

//Executes this block if condition is false

else
{
//Executes this block if condition is false
}

Example-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");

else

System.out.println("i is greater than 15");

else

System.out.println("i is greater than 15");

Output:

i is smaller than 15

4.if...else if...else Statement:

An if statement can be followed by an optional else if...else statement, which is veryuseful to test
various conditions using single if...else if statement.

Syntax:
if(Boolean_expression 1){

//Executes when the Boolean expression 1 is true

}else if(Boolean_expression 2){

//Executes when the Boolean expression 2 is true

}else if(Boolean_expression 3){

//Executes when the Boolean expression 3 is true

}else {
//Executes when the none of the above condition is true.
}

Example:

public class Test {

public static void main(String args[]){

Output:

Value of X is 30

5.switch Statement:

•​ The switch case statement, also called a case statement is a multi-way branch with several
choices. A switch is easier to implement than a series of if/else statements.

•​ A switch statement allows a variable to be tested for equality against a list of values. Eachvalue
is called a case, and the variable being switched on is checked for each case.

•​ The switch statement begins with a keyword, followed by an expression that equates to a no long
integral value. Following the controlling expression is a code block that contains zero or more labeled
cases. Each label must equate to an integer constant and each must be unique.

•​ When the switch statement executes, it compares the value of the controlling expression to the
values of each case label.

•​ The program will select the value of the case label that equals the value of the
controllingexpression and branch down that path to the end of the code block.

•​ If none of the case label values match, then none of the codes within the switch statementcode
block will be executed.

•​ Java includes a default label to use in cases where there are no matches. We can have a nested
switch within a case block of an outer switch.

Syntax:

switch (<expression>)
{

case label1:

<statement1> case label2:

<statement2>

case labeln:

<statementn> default:

<statement>}

Example:

public class SwitchCaseStatementDemo {

public static void main(String[] args) {int a = 10, b = 20, c = 30;

int status = -1;

if (a > b && a > c) {

status = 1;

} else if (b > c) {

status = 2;

} else {

status = 3;

switch (status) {

case 1:

System.out.println("a is the greatest");

break;

case 2:

System.out.println("b is the greatest");

break;

case 3:

System.out.println("c is the greatest");


break;

default:

System.out.println("Cannot be determined");

}}}

Output:

c is the greatest

Looping Statements (Iteration Statements)


1.While Statement

The while statement is a looping control statement that executes a blockof code while a condition
is true. It is entry controlled loop.You can either have a single statement or a block of code within
the while loop.The loop will never be executed if the testing expression evaluates to false.The
loop condition must be a boolean expression.

Syntax:
The syntax of the while loop is
while (<loop condition>)
{
<statements>
}


Example:

public class WhileLoopDemo {

public static void main(String[] args) {int count =


1;
System.out.println("Printing Numbers from
1 to 10"); while (count <= 10) {

System.out.println(count++);

}
}
}
Output
Printing Numbers from 1 to 10
1
2
3
​ ​ 4
5
6
7
8
9
10
2.do-while Loop Statement
do while loop checks the condition after executing the statements atleast once.
Therefore it is called as Exit Controlled Loop.
· The do-while loop is similar to the while loop, except that the test is performed at
the endof the loop instead of at the beginning.
· This ensures that the loop will be executed at least once. A do-while loop begins
with the keyword do, followed by the statements that make up the body of the loop.
Syntax:

do
{
<loop body>
}while (<loop condition>);

Example:
public class DoWhileLoopDemo {
public static void main(String[] args)
{
int count = 1;
System.out.println("Printing Numbers from
1 to 10"); do {
System.out.println(count++);
} while (count <= 10);
}
}
Output:
Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
10
3.For Loops

The for loop is a looping construct which can execute a set of instructions a
specifiednumber of times. It‘s a counter controlled loop. A for statement consumes the
initialization, condition and increment/decrement in one line. It is the entry controlled
loop.
Syntax:
for (<initialization>; <loop condition>; <increment expression>)
{
<loop body>
}
●​ The first part of a for statement is a starting initialization, which executes once
before the loop begins. The <initialization> section can also be a
comma-separatedlist of expression statements.
●​ The second part of a for statement is a test expression. As long as the
expression istrue, the loop will continue. If this expression is evaluated as false
the first time, theloop will never be executed.
●​ The third part of the for statement is the body of the loop. These are the
instructionsthat are repeated each time the program executes the loop.
●​ The final part of the for statement is an increment expression that automatically
executes after each repetition of the loop body. Typically, this statement
changes the value of the counter, which is then tested to see if the loop should
continue.

Exmple:
public class ForLoopDemo {
public static void main(String[] args)
{
System.out.println("Printing Numbers from 1 to 10");

for (int count = 1; count <= 10; count++)

{
System.out.println(count);
}}}
Output:
Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
10

Transfer Statements / Loop Control Statements/Jump Statements)


1. break statement
2. continue statement
1.break Statement

The break keyword is used to stop the entire loop. The break keyword must beused inside any loop or a
switch statement.The break keyword will stop the execution of the innermost loop and start
executingthenext line of code after the block.

Syntax:
The syntax of a break is a single statement inside any loop:
break:

Example:

public class Test {

public static void main(String args[]) {


int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
break;
}System.out.print( x ); System.out.print("\n");}}

Output:

10
20
2. Using continue Statement:
The continue keyword can be used in any of the loop control structures. It causes theloop to immediately
jump to the next iteration of the loop.The Java continue statement is used to continue loop. It continues
the current flow of the program and skips the remaining code at specified condition. In case of inner
loop, it continues only inner loop.
Syntax:
The syntax of a continue is a single statement inside any loop:
continue;
Example:
public class Test {
public static void main(String args[]) {int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers )
{
if( x == 30 )
{
continue;
}
System.out.print( x ); System.out.print("\n");
}}}

Output:
10
20
40
50

DEFINING CLASSES and OBJECTS

A class is a collection of similar objects and it contains data and methods that operate on that
data. In other words ― Class is a blueprint or template for a set of objects that share a
common structure and a common behavior.

DEFINING A CLASS:
The keyword class is used to define a class.
​ Rules to be followed:

1. Classes must be enclosed in parentheses.


2. ​ The class name, superclass name, instance variables and method names may be
any validJava identifiers.
3. ​ The instance variable declaration and the statements of the methods must end
with ;(semicolon).
4. ​ The keyword extends means derived from i.e. the class to the left of the
extends (subclass) is derived from the class to the right of the extends (superclass).
Syntax:
class ClassName {
datatype instance_variable1;
datatype instance_variable2;
...
returntype methodName(parameter_list) {
// method body
}
}
Instance Variables
●​ Variables defined within a class but outside methods are called instance variables.​

●​ Methods and variables inside a class define its structure.


EXAMPLE:

class box {

double width; double height; double depth; void volume()

{
System.out.println( \n Volume is : );
Systme.out.println(width*height*depth);
}

Objects
●​ An object is an instance of a class.

●​ An object has states (data) and behaviours (functions).​

Example of States: colour, name, breed​


Example of Behaviours: barking, eating

Object Declaration:

ClassName objectName;

Object Instantiation:

objectName = new ClassName();

Example:

Rectangle rect; // declaration

rect = new Rectangle(); // instantiation

Or:

Rectangle rect = new Rectangle();

ACCESSING CLASS MEMBERS:


Accessing the class members means accessing instance variable and instance methods in a class.To
access these members, a dot (.) operator is used along with the objects.
Syntax for accessing the instance members and methods

object_name.variable_name;

object_name.method_name(parameter_list);
Example:
class box

{
double width; double height;
double depth; void volume()
{
System.out.print("\n Box Volume is : ");
System.out.println(width*height*depth+" cu.cms");

}}

public class BoxVolume


{
public static void main(String[] args)
{
box b1=new box(); // creating object of type box
b1.width=10.00; ​ // Accessing instance
variables b1.height=10.00;
b1.depth=10.00;
b1.volume(); ​ // Accessing method through object
}
}
Output:

Box Volume is: 1000.0 cu.cms

Constructors
Definition:​
A constructor is a special type of method that is used to initialise the object. The constructor is
invoked at the time of object creation. Once defined, the constructor is automatically called
immediately after the object is created, before the new operator completes.

Syntax for Object Creation:

ClassName objectName = new ConstructorName();

Where:

●​ new → Keyword used to create an object.


●​ Constructor → Used to initialize the object.

If a constructor is not defined, the Java compiler builds a default constructor for that class.

Characteristics / Rules of Constructors

1.​ The constructor name must be the same as the class name.​

2.​ Constructors do not have a return type (not even void).​

3.​ At least one constructor will be invoked when an object is created.​

4.​ Constructors in Java cannot be final or static.

Syntax:

class ClassName {
ConstructorName() {
// initialization code
}
}
Example – Object Creation

class Student {

String name;

int sno;

Student() {

name = "ABC";

sno = 123;

public static void main(String[] args) {


Student st = new Student();
System.out.println(st.name);
System.out.println(st.sno);
}
}

Types of Constructors

1.​ Default (No-argument) Constructor

2.​ Parameterized Constructor

1) Default Constructor

A constructor with no parameters is known as the default constructor.​


It provides default values to the object like 0, null, etc., depending on the type.
Syntax:
class ClassName {
ClassName() {
// initialization
}
}
Example:
class Student {
String name;
int sno;

Student() {
name = "ABC";
sno = 123;
}
public static void main(String[] args) {
Student st = new Student();
System.out.println(st.name); // ABC
System.out.println(st.sno); // 123
}
}

2) Parameterised Constructor

A constructor with parameters is called a parameterised constructor.

Example:
class Student {
String name;
int sno;
Student(String n, int no) {
name = n;
sno = no;
}
public static void main(String[] args) {
Student s2 = new Student("Riya", 456);
System.out.println(s2.name); // Riya
System.out.println(s2.sno); // 456
}
}
Constructor Overloading

When a class contains more than one constructor with different parameter lists, it is called
constructor overloading.

Syntax:
class ClassName {
ClassName() { ... }
ClassName(parameter1, parameter2) { ... }
}
Example:
class Student {
String name;
int sno;

Student() {
name = "Anvi";
sno = 555;
}
Student(String n, int no) {
name = n;
sno = no;
}
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student("Eva", 253);

System.out.println(s1.name); // Anvi
System.out.println(s1.sno); // 555
System.out.println(s2.name); // Eva
System.out.println(s2.sno); // 253
}
}

Difference Between Constructors and Methods


Constructors Methods

Name must be same as class name Can have any name

No return type Must have a return type (can be void)

Called automatically when an object is created Called explicitly using object

Invoked only once when object is created Can be called multiple times

“this” KEYWORD:

Definition:
In java, this is a reference variable that refers to the current object.

Usage of this keyword

1. ​ this keyword can be used to refer current class instance variable.

2. ​ this() can be used to invoke current class constructor.

3. this keyword can be used to invoke current class method (implicitly)

4. ​ this can be passed as an argument in the method call.

5. ​ this can be passed as argument in the constructor call.

6. this keyword can also be used to return the current class instance.
Instance Variable Hiding:
It is illegal in Java to declare two local variables with the same name inside the same or
enclosing scopes. We can also have local variables, which overlap with the names of the class's instance
variables. However, when a local variable has the same name as an instance variable, the local
variable hides the instance variable .

We can use the “this” keyword to resolve any namespace collisions that might occur between
instance variables and local variables.

Example:
class Student
{
int rollno; String name; float fee;

Student(int rollno,String name,float fee)

{
this.rollno=rollno;
this.name=name; this.fee=fee;

void display()
{
System.out.println(rollno+" "+name+" "+fee);
}
}

class TestThis2

{
public static void main(String args[])
{
Student s1=new Student(111,"ankit",5000f); Student
s2=new Student(112,"sumit",6000f); s1.display();

s2.display();

}
}

Output:

ankit 5000
METHODS
DEFINITION :
A Java method is a collection of statements that are grouped to operate.
Syntax: Method:
modifier Return –type method_name(parameter_list) throws exception_list
{
// method body
}
The syntax shown above includes:

· modifier: It defines the access type of the method, and it is optional to use.
· returnType: Method may return a value.
· Method_name: This is the method name. The method signature consists of the method
name and the parameter list.
· Parameter List: The list of parameters includes the type, order, and number of
parameters of a method. These are optional; the method may contain zero parameters.
· Method body: The method body defines what the method does with statements.
Example:

This method takes two parameters num1 and num2 and returns the maximum between the two:
/** the snippet returns the minimum between two numbers
*/ public static int minFunction(int n1, int n2)

int min;
int findMin(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}

METHOD CALLING (Example for Method that takes parameters and returning value):
●​ For using a method, it should be called.​

●​ A method may take any number of arguments.​

●​ A parameter is a variable defined by a method that receives a value when the method is called.​

1.​ Example: In square(i), i is a parameter.​

●​ An argument is a value that is passed to a method when it is invoked.


1.​ Example: square(100) passes 100 as an argument. Inside square(), the parameter i
receives that value.​
●​ There are two ways in which a method is called:​

1.​ Calling a method that returns a value.​

2.​ Calling a method that returns nothing (no return value).​

●​ The process of method calling is simple:​

1.​ When a program invokes a method, program control gets transferred to the called
method.​

2.​ The called method then returns control to the caller in two conditions:​

■​ When the return statement is executed.​

■​ When the method’s closing brace } is reached.

Example:
Following is the example to demonstrate how to define a method and how to call it:
public class MinNumber

public static void main(String[] args)


{
int a = 11; int b = 6;
int c = minFunction(a, b);
System.out.println("Minimum Value
= " + c);
}
/** returns the minimum of two numbers */ public static int minFunction(int n1, int n2)

{
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}

This would produce the following


result: Minimum value = 6
Parameter Passing in Java

1.​ Pass by value / Call by value.​

2.​ Pass by reference / Call by reference.

Pass by Value

●​ In C: The method parameter is copied into the local parameter.​


No effect on the original copy.
●​ In Java:​

○​ Parameters are always passed by value.​

○​ Scalar variables: int, long, short, float, byte, double, char, boolean → are always passed
to methods by value.

○​ Non-scalar variables: Array, String are passed by reference.

Note:

●​ Scalar variable → Data with one value.

●​ Non-scalar variable → Data with multiple values.

Program: Pass by Value

class Swapper {
int a, b; // parameters
// Constructor to initialize variables
Swapper(int x, int y) {
a = x;
b = y;
}
void swap(int x, int y) {
int temp; // Local copy x, y gets swapped
temp = x; // Original object a, b unchanged
x = y;
y = temp;
}
}
class Main {
public static void main(String[] args) {
// main method content here
System.out.println("Before Swapping : a = " + obj.a + " b = " + obj.b);​
​ obj.swap(obj.a, obj.b); // call the method by passing values obj​
​ System.out.println("Before Swapping : a = " + obj.a + " b = " + obj.b);​
}

O/P: Before Swapping : a = 10 b = 20​


After Swapping : a = 10 b = 20
Pass by Reference:

●​ Reference (address) of the actual parameters is passed to the local parameters.

●​ Reflected on the actual parameter.

Program:
class Swapper
{
int a;
int b;
Swapper(int x, int y) // Initialize variables
{
a = x;
b = y;
}
void swap(Swapper ref)
{
int temp;
temp = ref.a;
ref.a = ref.b;
ref.b = temp;
}
}
class PassByRef
{
public static void main(String[] args)
{
Swapper obj = new Swapper(10, 20); // Create object
System.out.println("Before Swapping : a = " + obj.a + " b = " + obj.b);

obj.swap(obj); // call the method

System.out.println("After Swapping : a = " + obj.a + " b = " + obj.b);


}
}

O/P: Before Swapping : a = 10 b = 20​


After Swapping : a = 20 b = 10

Access Specifiers
Access specifiers or access modifiers in Java specify data members, methods, constructors, or classes.

Types of Access Specifiers:

1.​ private​

2.​ public​

3.​ protected​

4.​ default (no specifier)


Access Specifiers Table:
Access Modifiers Default Private Protected Public

Inside the class Yes Yes Yes Yes

Within a subclass (inside the same package) Yes No Yes Yes

Outside the package No No No Yes

Within the subclass (outside the package) No No Yes Yes

Private Access Modifier:

Private data fields and methods are accessible only inside the class where they are declared (same class
members).​
It supports encapsulation and abstraction.

Example:

class PrivateEx {
private int x; // private data
public int y; // public data

private PrivateEx() { // private constructor


}
public PrivateEx(int a, int b) { // public constructor
x = a;
y = b;
}
}

public class Main {

public static void main(String[] args) {

// PrivateEx obj1 = new PrivateEx(); // Error: private constructor cannot be applied

PrivateEx obj2 = new PrivateEx(10, 20); // public constructor applied

System.out.println(obj2.y); // public data y is accessible

// System.out.println(obj2.x); // Error: x has private access

O/P: Compile time error for private members.


Default Access Modifier:

Default specifier allows access to classes, methods, or fields within the same package but not from
outside the package.

Example

class DefaultEx {
int y = 10; // default data
}
public class Main {
public static void main(String[] args) {
DefaultEx obj = new DefaultEx();
System.out.println(obj.y); // default data y is accessible outside the class but within the same
package
}
}

O/P: 10

Protected Access Modifier:

Protected methods and fields are accessible:

●​ Within the same class​

●​ Subclasses inside the same package​

●​ Subclasses in other packages

Example:
class Base {
protected void show() {
System.out.println("In Base");
}
}
public class Main extends Base {
public static void main(String[] args) {
Main obj = new Main();
obj.show(); // calling protected method
}
}

O/P: In Base

Public Access Modifier:

●​ The public access specifier has the highest level of accessibility.​

●​ Methods, classes, and fields declared as public are accessible by any class in the same or
different package.
Example:

class PublicEx {
public int no = 10;
}
public class Main {
public static void main(String[] args) {
PublicEx obj = new PublicEx();
System.out.println(obj.no);
}
}
O/P: 10
Static Members:
Static Members are data members (variables) or methods that belong to a static or non-static
class rather than to the objects of the class. Hence it is not necessary to create object of that class
to invoke static members.
The static can be:
1. variable (also known as class variable)
2. method (also known as class method)
3. block
4. nested class
Static Variable:

When a member variable is declared with the static keyword, then it is called static variable and it
can be accessed before any objects of its class are created, and without reference to any object.
Syntax
[access_spefier] static data_type instance_variable;
When a static variable is loaded in memory (static pool) it creates only a single copy of the static
variable and is shared among all the objects of the class. A static variable can be accessed outside
of its class directly by the class name and doesn‘t need any object.
Syntax : <class-name>.<variable-name>

Advantages of static variable

It makes your program memory efficient (i.e., it saves memory).


Static Method:
If a method is declared with the static keyword , then it is known as static method.
A static method belongs to the class rather than the object of a class.
A static method can be invoked without the need for creating an instance of a class.
A static method can access static data member and can change the value of it.
Static members →

●​ Static data member


●​ Static 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.
Static Block:

Static block is used to initialize the static data member like constructors helps toinitialize instance
members and it gets executed exactly once, when the class is first loaded.It is executed before main
method at the time of class loading in JVM.

Syntex:

class classname
{
static
{
// block of statements
}
}

Example:
class StaticProg {
static int a = 10;
static void fun(int b) {
System.out.println("b = " + b);
System.out.println("a = " + a);
}
}
class AnotherClass {
public static void main(String[] args) {
System.out.println("a = " + StaticProg.a);
StaticProg.fun(20);
}
O/P:
a = 10
b = 20
a = 10

JavaDoc Comments:
●​ Javadoc is a convenient tool.​

●​ Javadoc is a special format of comments.​

●​ Generates an HTML document based on the comments.​

●​ HTML files give the convenience of hyperlinks from one document to another.

Input: Java source files (.java)

· Individual source files

· ​ Root directory of the source files


Output: HTML files documenting the specification of java code

· One file for each class is defined

· Package and overview files


HOW TO INSERT COMMENTS?
The javadoc utility extracts information for the following items:
• Packages
• Public classes and interfaces
• Public and protected methods
• Public and protected fields
Each comment is placed immediately above the feature it describes.
Format:
A Javadoc comment is similar to a multi-line comment except that it begins with a
forward slash followed by two asterisks (/**) and ends with a */
Each /** . . . */ documentation comment contains free-form text followed by tags.
A tag starts with an @, such as @author or @param.
The first sentence of the free-form text should be a summary statement.
The javadoc utility automatically generates summary pages that extract thesesentences.
In the free-form text, you can use HTML modifiers such as <em>...</em> foremphasis,
<code>...</code> for a monospaced-typewriter font, <strong>...</strong> for strong
emphasis, and even <img ...> to include an image.
Example:

/**
This is a <b>doc</b> comment.
*/

Types:

Javadoc comments​
→ Class level comments​
→ Member-level comments

Note:​
Javadoc comments start with /** and end with */.

TYPES OF COMMENTS:
1.Class Comments
The class comment must be placed after any import statements, directly before the classdefinition.
Example:
import java.io.*;
/** class comments should be written here */Public class sample
{
….
}
2.Method Comments

The method comments must be placed immediately before the method that it describes.

Tags used:

Tag Description Syntax


@param It describes the method parameter @param name description

@return This tag describes the return value from a @return description
method with the exception void methods
and constructors.
@throw s This tag describes the method that throws @throws class description
an exception.

Example:
/** adding two numbers
@param a & b are two numbers to be added @return the result of addition
**/
public double add(int a,int b)
{
int c=a+b; return c;
}

3. Field Comments
Field comments are used to document public fields—generally, that means static constants.

For example:
/**

* Account number

*/

public static final int acc_no = 101;

4.General Comments

Tag Description Syntax

The following tags can be used in class documentation comments

@author This tag makes an ―author entry. You can have multiple @author name
@author tags, one for each author.

This tag makes a ―version‖ entry. The text can


@version be any description of the current version. @version text

The following tags can be used in all documentation comments


This tag makes a ―since‖ entry. The text can be any
@since description of the version that introduced thisfeature. @since text
For example, @since version 1.7.1
@deprecate d This tag adds a comment that the class, method, or variable @deprecated text
should no longer be used. The text should suggest a
replacement.For example:
@deprecated Use <code>setVisible(true)</code>instead
Hyperlinks to other relevant parts of the javadoc documentation, or to external
documents,with the @see and @link tags.
This tag place hyperlinks to other classes or methods
@link anywhere in any of your documentationcomments. {@link
package.class#feature
label}

@see This tag adds a hyperlink in the ―see also section. It @see reference
can be used with both classes and methods. Here,
reference can be one of the following:

package.class#feature label

<a ref="...">label</a> "text"

Example:

@see ―Core java 2


@see <a href=222.java.com>Core Java</a>

COMMENT EXTRACTION

Here, docDirectory is the name of the directory where you want the HTML files to go. Follow these
steps:
1. Change to the directory that contains the source files you want to document.
2. To create the document API, you need to use the javadoc tool followed by java file name.There is no
need to compile the Java file.
Here, docDirectory is the name of the directory where you want the HTML files to go.

Follow these steps:

1.​ Change to the directory that contains the source files you want to document.

2.​ Run the command

javadoc -d docDirectory nameOfPackage

for a single package. Or run

javadoc -d docDirectory nameOfPackage1 nameOfPackage2...

to document multiple packages.

If your files are in the default package, then instead run

javadoc -d docDirectory *.java


If you omit the -d docDirectory option, then the HTML files are extracted to the currentdirectory.

Example:

//Java program to illustrate frequently used

// Comment tags

/**

* <h1>Find average of three numbers!</h1>

* The FindAvg program implements an application that

* simply calculates average of three integers and Prints

* the output on the screen.

*​

* @author Pratik Agarwal

* @version 1.0

* @since 2017-02-18

*/

public class FindAvg

/**

* This method is used to find average of three integers.

* @param numA This is the first parameter to findAvg method

* @param numB This is the second parameter to findAvg method

* @param numC This is the third parameter to findAvg method

* @return int This returns average of numA, numB and numC.

*/

public int findAvg(int numA, int numB, int numC)

return (numA + numB + numC)/3;


}

/**

* This is the main method which makes use of findAvg method.

* @param args Unused.


* @return Nothing.

*/

public static void main(String args[])

FindAvg obj = new FindAvg();

int avg = obj.findAvg(10, 20, 30);

System.out.println("Average of 10, 20 and 30 is :" + avg);

OUTPUT:

D:\OOPs\Programs\JavaDoc>javadoc -d FindAvgDocument FindAvg.java

Loading source file FindAvg.java... Constructing Javadoc information...

Creating destination directory: "FindAvgDocument\" Standard Doclet version 1.8.0_251

DOWNLOADED FROM STUCOR APP

Building tree for all the packages and classes... Generating FindAvgDocument\FindAvg.html...
FindAvg.java:32: error: invalid use of @return

* @return Nothing.

Generating FindAvgDocument\package-frame.html... Generating


FindAvgDocument\package-summary.html... Generating FindAvgDocument\package-tree.html...

Generating FindAvgDocument\constant-values.html... Building index for all the packages and classes...

Generating FindAvgDocument\overview-tree.html... Generating FindAvgDocument\index-all.html...

Generating FindAvgDocument\deprecated-list.html... Building index for all classes...

Generating FindAvgDocument\allclasses-frame.html... Generating


FindAvgDocument\allclasses-noframe.html... Generating FindAvgDocument\index.html...

Generating FindAvgDocument\help-doc.html... 1 error

You might also like