SlideShare a Scribd company logo
1 of 54
UNIT I
INTRODUCTION TO OOP AND JAVA
Overview of OOP – Object oriented programming paradigms – Features of Object
Oriented Programming – Java Buzzwords – Overview of Java – Data Types, Variables
and Arrays – Operators – Control Statements – Programming Structures in Java –
Defining classes in Java – Constructors -Methods -Access specifiers - Static members-
Java Doc comments
Object Oriented Programming Paradigms
 The object oriented programming approach is developed in order to remove some of
the flaws of procedural programming.
 OOP has a complete focus on data and not on the procedures. In OOP, the data can be
protected from accidental modification.
 In OOP the most important entity called object is created.
 Each object consists of data attributes and the methods. The methods or functions
operate on data attributes.
Difference Between Procedural Programming and Object Oriented Programming (Nov-
Dec 2022)
Procedure-Oriented Programming Object-Oriented Programming
 Divided into  In POP, program is divided into small
parts called functions.
 In OOP, program is divided into
parts called objects.
 Importance  In POP, Importance is not given to data
but to functions as well as sequence of
actions to be done.
 In OOP, Importance is given to the
data rather than procedures or
functions because it works as a real
world.
 Approach  POP follows Top Down approach.  OOP follows Bottom Up approach.
 Access
Specifiers
 POP does not have any access specifier.  OOP has access specifiers named
Public, Private, Protected, etc.
 Data
Moving
 In POP, Data can move freely from
function to function in the system.
 In OOP, objects can move and
communicate with each other
through member functions.
 Expansion  To add new data and function in POP is
not so easy.
 OOP provides an easy way to add
new data and function.
 Data Access  In POP, Most function uses Global data
for sharing that can be accessed freely
from function to function in the system.
 In OOP, data cannot move easily
from function to function, it can be
kept public or private so we can
control the access of data.
 Data Hiding  POP does not have any proper way for
hiding data so it is less secure.
 OOP provides Data Hiding so
provides more security.
 Overloading  In POP, Overloading is not possible.  In OOP, overloading is possible in
the form of Function Overloading
and Operator Overloading.
 Examples  Example of POP are: C, VB, FORTRAN,
Pascal.
 Example of OOP are: C++, JAVA,
VB.NET, C#.NET.
Features of Object Oriented Programming (Nov – Dec 2022)
Fundamental principles of OOPS
OOPS Concepts
 Object
o Objects are basic run-time entities in object oriented programming.
o Object represent a person, place or any item that a program handles.
o A single class can create any number of objects.
o Object occupies memory
o Every object has data structures called attributes (data) and behaviour called
operations (methods/fucntions).
o Declaring objects -
 The syntax for declaring object is - Class Name Object_Name;
 Fruit f1;
 For the class Fruit the object f1 can be created.
 Classes
o A class is a user defined prototype for object creation.
o Class does not occupy memory.
o In Java, class keyword is used to declare the class.
o A class can be defined as an entity in which data and functions are put
together.
o The concept of class is similar to the concept of structure in C.
Syntax :
class name_of_class
{
private:
variables declarations;
function declarations;
public:
variable declarations;
function declarations;
}; do not forget semicolon
Difference between class and Objects
Object Class
 Object is an instance of a class.  Class is a blueprint or template
from which objects are created
 Object is a real world entity such
aspen, laptop, mobile, bed,
keyboard, mouse, chair etc
 Class is a group of similar objects.
 Object is a physical entity.  Class is a logical entity
 Object is created through new
keyword mainly e.g.
Student s1=new Student();
 Class is declared using class
keyword
e.g.class Student{}
 Object is created many times as per
requirement.
 Class is declared once.
 Object allocates memory when it is
created.
 Class doesn't allocated memory
when it is created.
 Encapsulation
o Definition: The wrapping up of data and methods into a single unit is known as
encapsulation.
o The data inside that class is accessible by the function in the same class. It is
normally not accessible from the outside of the component.
o This protection mechanism is called data hiding or information hiding.
 Abstraction
o Definition: Abstraction means representing only essential features by
hiding all the implementation details.
o In object oriented programming languages like C++, or Java class is an entity
used for data abstraction purpose.
Example
class Student
{
int roll;
char name [10];
public;
void input ();
void display();
}
In main function we can access the functionalities using object. For instance
Student obj;
obj.input();
obj.display ();
Thus only abstract representation can be presented, using class.
 Inheritance:
o Definition: Inheritance is a property by which the new classes are created
using the old classes. In other words the new classes can be developed using
some of the properties of old classes.
o Inheritance support hierarchical structure.
o The old classes are referred as base classes and the new classes are referred as
derived classes. That means the derived classes inherit the properties (data and
functions) of base class.
Example: Here the Shape is a base class from which the Circle, Line and
Rectangle are the derived classes. These classes inherit the functionality draw()
and resize(). Similarly the Rectangle is a base class for the derived class Square.
Along with the derived properties the derived class can have its own properties.
For example the class Circle may have the function like backgrcolor() for
defining the back ground color.
 Polymorphism
o Definition: Polymorphism in java is a concept by which we can perform a single
action by different ways.
o Polymorphism is derived from 2 (two) greek words: poly and morphs.
o The word “poly” means many and “morphs” means forms. So, polymorphism
means many forms.
o Real Time Example:
 In a class there will be more students with a same name. We can
differentiate the students with their initial, register number etc.,
Features of Java/ Java Buzzwords/Characteristics of Java
 Platform Independent
 Object Oriented Concepts
 Simple
 Secure
 Robust
 Portable
 Multithreading
 Distributed Applications
 Architectural Neutral
Platform Independent:
 On compilation Java program is compiled into bytecode.
 Byte code is an intermediate code generated from the source code by java compiler
and it is platform independent.
 This bytecode is platform independent and can be run on any machine, plus this
bytecode format also provide security.
 Any machine with Java Runtime Environment can run Java Programs.
 Java is guaranteed to be write-once, run-anywhere language.
Object Oriented
 In java, everything is an object which has some data and behaviour. Java can be easily
extended as it is based on Object Model. Following are some basic concept of OOP's.
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Simple
 Java is very easy to learn, and its syntax is simple, clean and easy to understand.
 Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
 There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
Secure
 The instructions of bytecode is executed by the Java Virtual Machine (JVM). That
means JVM converts the bytecode to machine readable form.
 JVM understand only the bytecode and therefore any infectious code cannot be
executed by JVM. No virus can infect bytecode. Hence it is difficult to trap the
internet and network based applications by the hackers.
Robust
 Java is robust because:
o It uses strong memory management.
o There is a lack of pointers that avoids security problems.
o Java provides automatic garbage collection which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.
o There are exception handling and the type checking mechanism in Java.
Portable
 Java program written in one environment can be executed in another environment.
Multithreading
 Concurrent execution of several parts of same program at the same time.
 The main advantage of multi-threading is that it doesn't occupy memory for each
thread. It shares a common memory area.
Distributed Applications
 This feature is very much useful in networking environment.
 In Java, two different objects on different computers can communicate with each other.
 This can be achieved by Remote Method Invocation (RMI).
Architectural Neutral
 Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.
 In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and
4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for
both 32 and 64-bit architectures in Java.
Operators
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operators
 Bitwise Operators
 Unary Operators
 Ternary Operator
 Instanceof operator
Arithmetic operators
 Java arithmetic operators are used to perform addition, subtraction, multiplication, and
division. They act as basic mathematical operations.
Operator Description
+ adds two operands
- subtract second operands from first
* multiply two operand
/ divide numerator by denominator
% remainder of division
++
Increment operator increases integer
value by one
--
Decrement operator decreases integer
value by one
Example program for Arithmetic Operators Output
import java.util.Scanner;
class Arithmetic_operators1{
public static void main(String args[])
{
Scanner in1=new Scanner(System.in);
System.out.println("Enter two values");
int a=in1.nextInt();
int b=in1.nextInt();
int c;
c=a+b;
System.out.println("Addition: "+c);
c=a-b;
System.out.println("Subtraction: "+c);
c=a*b;
System.out.println("Multiplication: "+c);
c=a/b;
System.out.println("Division: "+c);
b=3;
c=a%b;
Enter two values
10
2
Addition: 12
Subtraction: 8
Multiplication: 20
Division: 5
Remainder: 1
Increment Operator: 11
decrement Operator: 10
System.out.println("Remainder: "+c);
a=++a;
System.out.println("Increment Operator: "+a);
a=--a;
System.out.println("decrement Operator: "+a);
}
}
Relation operators
 Relational operators are used to test comparison between operands or values. It can be
use to test whether two values are equal or not equal or less than or greater than etc.
Operator Description
= = Check if two operand are equal
!= Check if two operand are not equal.
> Check if operand on the left is greater than operand on the right
< Check operand on the left is smaller than right operand
>= check left operand is greater than or equal to right operand
<= Check if operand on left is smaller than or equal to right operand
Example program for Relational Operators Output
import java.util.Scanner;
class Arithmetic_operators1{
public static void main(String args[])
{
Scanner in1=new Scanner(System.in);
System.out.println("Enter two values");
int a=in1.nextInt();
int b=in1.nextInt();
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}
Enter two values
40
30
a == b = false
a != b = true
a > b = true
a < b = false
b >= a = false
b <= a = true
Logical Operators
 Logical operators are used to check whether an expression is true or false.
Operator Meaning
&& (Logical AND) true only if both expression1 and
expression2 are true
|| (Logical OR) true if either expression1 or expression2 is
true
! (Logical NOT) true if expression is false and vice versa
Example program for logical Operators Output
class Main {
public static void main(String[] args) {
// && operator
System.out.println((5 > 3) && (8 > 5)); // true
System.out.println((5 > 3) && (8 < 5)); // false
// || operator
System.out.println((5 < 3) || (8 > 5)); // true
System.out.println((5 > 3) || (8 < 5)); // true
System.out.println((5 < 3) || (8 < 5)); // false
// ! operator
System.out.println(!(5 == 3)); // true
System.out.println(!(5 > 3)); // false
}
}
true
false
true
true
false
true
false
Assignment Operators
Assignment operators are used in Java to assign values to variables. For example,
int age;
age = 5;
Here, = is the assignment operator. It assigns the value on its right to the variable on its left.
That is, 5 is assigned to the variable age.
Operator Example Equivalent to
= a=b; a=b;
+= a += b; a = a + b;
-= a -= b; a = a - b;
*= a *= b; a = a * b;
/= a /= b; a = a / b;
%= a %= b; a = a % b;
Program for Assignment Operators Output
public class Assignment{
public static void main(String[] args) {
int a = 10;
int b=20;
int c;
System.out.println(c = a); // Output =10
System.out.println(b += a);// Output=30
System.out.println(b -= a);// Output=20
System.out.println(b *= a);// Output=200
System.out.println(b /= a);// Output=20
System.out.println(b %= a);// Output=0
}
}
10
30
20
200
20
0
Bitwise operators
 Bitwise operators are used to perform operations bit by bit.
 Java defines several bitwise operators that can be applied to the integer types long, int,
short, char and byte.
 The following table shows all bitwise operators supported by Java.
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< left shift
>> right shift
Now lets see truth table for bitwise &, | and ^
a b a & b a | b a ^ b
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
The bitwise shift operators shifts the bit value. The left operand specifies the value to be shifted
and the right operand specifies the number of positions that the bits in the value are to be
shifted. Both operands have the same precedence.
Program for Bitwise Operators Output
public class Main{
public static void main(String[] args) {
int a=4, b=3;
System.out.println(a&b);
System.out.println(a|b);
System.out.println(a^b);
System.out.println(a<<2);
System.out.println(a>>2);
System.out.println(~a);
}
}
0
7
7
16
1
-5
Unary Operator
Incrementing/decrementing a value by one
Java also provides increment and decrement operators: ++ and -- respectively. ++ increases the
value of the operand by 1, while -- decrease it by 1.
1. public class OperatorExample{
2. public static void main(String args[]){
3. int x=10;
4. System.out.println(x++);//10 (11)
5. System.out.println(++x);//12
6. System.out.println(x--);//12 (11)
7. System.out.println(--x);//10
8. }}
10
12
12
10
Java Ternary Operator/ Conditional Operator
 The ternary operator (conditional operator) is shorthand for the if-then-else statement.
For example,
 variable = Expression ? expression1 : expression2
Here's how it works.
 If the Expression is true, expression1 is assigned to the variable.
 If the Expression is false, expression2 is assigned to the variable.
Example for Ternary Operator Output
class Java {
public static void main(String[] args) {
int februaryDays = 29;
String result;
// ternary operator
result = (februaryDays == 28) ? "Not a leap year" : "Leap year";
System.out.println(result);
}
}
Leap year
Java instanceof Operator
 The instanceof operator checks whether an object is an instanceof a particular class.
Example for Ternary Operator Output
class Main {
public static void main(String[] args) {
String str = "Akshaya";
boolean result;
// checks if str is an instance of
// the String class
result = str instanceof String;
System.out.println("Is str an object of String? " + result);
}
}
Is str an object of String? true
Arrays
 An array is a collection of similar data types.
 Array is a container object that hold values of homogeneous type. It is also known as
static data structure because size of an array must be specified at the time of its
declaration.
 Array starts from zero index and goes to n-1 where n is length of the array.
 Each element in the array can be accessed by using the index number.
 In java array is an Object.
 There are two types of arrays –
o One dimensional arrays
o Two dimensional arrays
 One Dimensional Array
o Represented using single index
o The syntax of declaring array is –
 data_type array_name[ ];
o and to allocate the memory –
 array_name=new data_type[size];
o We can combine both declaration and initialization in a single statement.
 Datatype[] arrayName = new datatype[size]
Initializing All Array Elements to Zero Output
public class InitializeDemo
{
public static void main(String[] args)
{
//Declaring array
int[] intArray;
//Initializing to Zero
intArray = new int[5];
//Printing the values
for(int i = 0; i < intArray.length; i++)
System.out.println(intArray[i]);
}
}
0
0
0
0
0
For string array the default value is null Output
public class InitializeDemo
{
public static void main(String[] args)
{
//Declaring array
String[] strArray;
//Initializing to Zero
strArray = new String[5];
//Printing the values
for(int i = 0; i < strArray.length; i++)
System.out.println(strArray[i]);
}
}
null
null
null
null
null
Program to take user input to initialize an array by using the
Scanner class
Output
import java.util.Scanner;
public class InitializeDemo
{
public static void main(String[] args)
{
//Declaring array
int[] intArray;
//Defining the array length
intArray = new int[5];
Enter the values:
5
10
15
20
25
The array contains:
5
10
15
Scanner s = new Scanner(System.in);
System.out.println("Enter the values: ");
//Initializing
for(int i = 0; i < intArray.length; i++)
intArray[i] = s.nextInt();
s.close();
System.out.println("The array contains: ");
//Printing the values
for(int i = 0; i < intArray.length; i++)
System.out.println(intArray[i]);
}
}
20
25
Initializing an Array at the time Declaration Output
public class InitializeDemo
{
public static void main(String[] args)
{
//Declaring array
int[] intArray = {3,6,9,12,15};
//Printing the values
for(int i = 0; i < intArray.length; i++)
System.out.println(intArray[i]);
}
}
3
6
9
12
15
Two – dimensional Array (2D-Array)
 Two – dimensional array is the simplest form of a multidimensional array.
 Two Dimensional Array can be represented as the collection of rows and columns.
 Declaration – Syntax:
o data_type[][] array_name = new data_type[x][y];
 Initialization – Syntax:
o array_name[row_index][column_index] = value;
o For example: arr[0][0] = 1;
 Direct Method of Declaration: Syntax:
o data_type[][] array_name = {
{valueR1C1, valueR1C2, ....},
{valueR2C1, valueR2C2, ....}
};
Java program that takes a two-dimensional array as input. Output
import java.util.Scanner;
public class ArrayInputExample2
{
public static void main(String args[])
{
int m, n, i, j;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the number of rows: ");
//taking row as input
m = sc.nextInt();
System.out.print("Enter the number of columns: ");
//taking column as input
n = sc.nextInt();
// Declaring the two-dimensional matrix
int array[][] = new int[m][n];
// Read the matrix values
System.out.println("Enter the elements of the array: ");
//loop for row
for (i = 0; i < m; i++)
//inner for loop for column
for (j = 0; j < n; j++)
array[i][j] = sc.nextInt();
//accessing array elements
System.out.println("Elements of the array are: ");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
//prints the array elements
System.out.print(array[i][j] + " ");
//throws the cursor to the next line
System.out.println();
}
}
}
Program for direct method of declaration Output
import java.io.*;
class GFG {
public static void main(String[] args)
{
int[][] arr = { { 1, 2 }, { 3, 4 } };
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
System.out.println("arr[" + i + "][" + j + "] = "+ arr[i][j]);
}
}
arr[0][0] = 1
arr[0][1] = 2
arr[1][0] = 3
arr[1][1] = 4
Accessing elements of Two Dimensional Array Output
import java.io.*;
class GFG {
public static void main(String[] args)
{
int[][] arr = { { 1, 2 }, { 3, 4 } };
System.out.println("arr[0][0] = " + arr[0][0]);
}
}
arr[0][0] = 1
Constructors (Nov/Dec 2022)
 Definition: The constructor is a specialized method for initializing objects.
 Name of the constructor is same as that of its class name. In other words, the name of
the constructor and class name is same.
 Whenever an object of its associated class is created, the constructor is invoked
automatically.
 The constructor is called constructor because it creates values for data fields of class.
Program for Default and parameterised constructor Output
public class Rectangle 1 {
int height;
int width;
Rectangle1()
{
System.out.println(" Simple constructor: values are initialised...");
height=10;
width=20;
}
Rectangle1 (int h,int w)
{
System.out.println(" Parameterised constructor: values are initialised...");
height=h;
width=w;
}
void area()
{
System.out.println("Now, The function is called...");
F:test>javac Rectangle1.java
F:test>java Constr_Demo
Simple constructor: values are
initialised...
Now, The function is called...
The area is 200
Parameterised constructor:
values are initialised...
Now, The function is called...
The area is 220
F:test>
Data fields
Simple constructor
Parameterized constructor
Method defined
int result height*width;
System.out.println("The area is "+result);
}
class Constr_Demo {
public static void main(String args[])
{
Rectangle1 obj = new Rectangle 1();
obj.area();//call the to method
Rectangle1 obj1 = new Rectangle 1(11,20);
obj1.area();//call the to method
}
}
Properties of constructor
 Name of constructor must be the same as the name of the class for which it is being
used.
 The constructor must be declared in the public mode.
 The constructor gets invoked automatically when an object gets created.
 The constructor should not have any return type. Even a void data type should not be
written for the constructor.
 The constructor cannot be used as a member of union or structure.
 The constructors can have default arguments.
 The constructor cannot be inherited.
 Constructor can make use of new or delete operators for allocating or releasing memory
respectively.
 Constructor cannot be virtual.
 Multiple constructors can be used by the same class.
 When we declare the constructor explicitly then we must declare the object of that class.
Defining classes in Java
Defining a class
 A class is a group of objects which have common properties.
 It is a template or blueprint from which objects are created.
 It is a logical entity.
Object created and simple
constructor is invoked
Object created and
parameterized
constructor is invoked
 It can’t be physical.
 A class in Java can contain:
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
Syntax to declare a class:
class <class_name>{
field;
method;
}
Instance variable in Java
o A variable which is created inside the class but outside the method is known as an
instance variable.
o Instance variable doesn't get memory at compile time.
o It gets memory at runtime when an object or instance is created.
o That is why it is known as an instance variable.
Object and Class Example: main within the class
Here, we are creating a main() method inside the class.
Java Program to illustrate how to define a class and
fields
Output
1. class Student{
int id;
1. String name;
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
0
null
Object and Class Example: main outside the class
o In real time development, we create classes and use it from another class.
o It is a better approach than previous one.
o Let's see a simple example, where we are having main () method in another class.
Java Program to demonstrate having the main method
in another class
Output
class Student{
int id;
String name;
0
null
}
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
3 Ways to initialize object
There are 3 ways to initialize object in Java.
o By reference variable
o By method
o By constructor
1) Object and Class Example: Initialization through reference
Initializing an object means storing data into the object. Let's see a simple example where we
are going to initialize the object through a reference variable.
Object and Class Example: Initialization through
reference
Output
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Akshaya";
System.out.println(s1.id+" "+s1.name);
}
}
101
Akshaya
2) Object and Class Example: Initialization through method
In this example, we are creating the two objects of Student class and initializing the value to
these objects by invoking the insertRecord method.
Object and Class Example: Initialization through method Output
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
111 Karan
222 Aryan
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
As you can see in the above figure, object gets the memory in heap memory area. The reference
variable refers to the object allocated in the heap memory area. Here, s1 and s2 both are
reference variables that refer to the objects allocated in memory.
Object and Class Example: Initialization through a constructor
Object and Class Example: Initialization through a constructor Output
class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
101 ajeet 45000.0
102 irfan 25000.0
103 nakul 55000.0
void display(){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
}
}
Object & Class Example: Rectangle Output
class Rectangle{
int length;
int width;
void insert(int l,int w){
length=l;
width=w;
}
void
calculateArea(){System.out.println(length*width);}
}
class TestRectangle2{
public static void main(String args[]){
Rectangle r1=new Rectangle(),
r2=new Rectangle();//creating two objects
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
55
45
Access Specifiers
 Access modifiers control access to data fields, methods, and classes. There are three
modifiers used in Java –
 public
 private
 default modifier
 public allows classes, methods and data fields accessible from any class
 private allows classes, methods and data fields accessible only from within the own
class.
 If public or private is not used then by default the classes, methods, data fields are
assessable by any class in the same package. This is called package-private or package-
access. A package is essentially grouping of classes.
Example program to demonstrate the usage of access specifiers.
package Test;
public class class1
{
public int a;
int b;
private int c;
public void fun1() {
}
void fun2() {
}
private void fun3() {
}
}
public class class2
{
void My_method() {
class 1 obj=new class1();
obj.a;//allowed
obj.b;//allowed
obj.c;//error:cannot access
obj.fun1();//allowed
package another Test
public class class3
{
void My_method()
class1 obj=new class1();
obj.a;//allowed
obj.b;// error:cannot access
obj.c;//error:cannot access
obj.fun1();//allowed
obj.fun2()//error:cannot access
obj.fun3()//error:cannot access
}
}
obj.fun2();//allowed
obj.fun3();//error:cannot access
}
}
 Protected mode is another access specifier which is used in inheritance.
 The protected mode allows accessing the members to all the classes and subclasses in
the same package as well as to the subclasses in other package.
 But the non subclasses in other package cannot access the protected members.
The effect of access specifiers for class, subclass or package is enlisted below-
Static Members
 The static members can be static data member or static method.
 The static members are those members which can be accessed without using object.
Program to introduce the use of the static method
and static variables
Output
class StaticProg
{
static int a = 10;
static void fun(int b)
{
System.out.println("b= "+b);
System.out.println("a = "+a);
}
}
class AnotherClass
a= 10
b= 20
a= 10
{
public static void main(String[] args)
{
System.out.println("a= "+Static Prog.a);
StaticProg.fun(20);
}
}
Program Explanation
In above program, we have declared one static variable a and a static member
function fun(). These static members are declared in one class StaticProg. Then we have
written one more class in which the main method is defined. This class is named as
AnotherClass. From this class the static members of class StaticProg are accessed without
using any object.
Syntax:
ClassName.staticMember
Points to Remember
 In Java the main is always static method.
 The static methods must can access only static data.
 The static method can call only the static method and cannot call a non-static
method.
 The static method cannot refer to this pointer.
 The static method cannot refer to super method.
Java Data types (Nov/Dec 2021)
 Java is a statically typed and also a strongly typed language.
 In Java, each type of data (such as integer, character, hexadecimal, etc. ) is predefined
as part of the programming language and all constants or variables defined within a
given program must be described with one of the data types
Data types represent the different values to be stored in the variable. In java, there are two
categories of data types:
 Primitive data types
 Non-primitive data types
The Primitive Types
Java defines eight primitive types of data: byte, short, int, long, char, float, double, and boolean.
1. Integers
 This group includes byte, short, int, and long.
 All of these are signed, positive and negative values.
Name Width in bits Range
long 64 –9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
int 32 –2,147,483,648 to 2,147,483,647
short 16 –32,768 to 32,767
byte 8 –128 to 127
2. Float-point numbers:
 They are also known as real numbers.
 This group includes float and double, which represents single- and double-
precision numbers, respectively.
Name Width in bits Range
double 64 4.9e–324 to 1.8e+308
float 32 1.4e–045 to 3.4e+038
3. Characters - This group includes char, which represents symbols in a character set like
letters and numbers. Char is 16-bit type. The range of a char is 0 to 65,536.
4. Boolean: This group includes boolean. It can have only one of two possible values, true
or false.
This program introduces use of various
data type in the program
Output
class DatatypeDemo
{
public static void main(String args[])
{
The value of a=: 10
The value of b=: 1280
The value of c=: 1280000
The value of d=: 1280000000
byte a=10;
short b=10*128;
int c=10000* 128;
long d=10000*1000*128;
double e=99.9998;
char f='a';
boolean g=true;
boolean h=false;
dynamic initialization
System.out.println("The value of a=: "+a);
System.out.println("The value of b=: "+b);
System.out.println("The value of c=: "+c);
System.out.println("The value of d=: "+d);
System.out.println("The value of e=: "+e);
System.out.println("The value of f=: "+f);
f++;
System.out.println("The value of f after
increment=: "+f);
System.out.println("The value of g=: "+g);
System.out.println("The value of h=: "+h);
}
}
The value of e=: 99.9998
The value of f=: a
The value of f after increment=: b
The value of g=: true
The value of h=: false
Control Statements (Nov/Dec 2020)
 Control statements in Java is one of the fundamentals required for Java Programming.
 It allows the smooth flow of a program.
 Control Statements are divided into three categories, namely
o Selection statements/ Decision making statements
o Iteration Statements/ Looping Statements
Selection Statements
 Simple if statement
 if else statement
 nested if statement
 if-else-if ladder
 Switch statement
Simple 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
be executed.
 Syntax:
if(<conditional expression>)
{
< Statement Action>
}
//Java Program for implementation of if statement Output
import java.util.Scanner;
public class Main
{
public static void main(String []args)
{
//Take input from the user
//Create an instance of the Scanner class
Scanner sc=new Scanner(System.in);
System.out.println("Enter the age: ");
int age=sc.nextInt();
if(age>=18)
{
System.out.println("The person is eligible to vote");
}
}
}
Enter the age: 21
The person is eligible to vote
if-else statement
 The if-else statement is used for testing condition. If the condition is true, if block
executes otherwise else block executes.
 The else block execute only when condition is false.
Syntax:
if(<conditional expression>)
{
< Statement Action1>
}
else
{
< Statement Action2>
}
//Java Program for implementation of if-else statement Output
import java.util.Scanner;
public class Main
{
public static void main(String []args)
{
//Take input from the user
//Create an instance of the Scanner class
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number: ");
int num=sc.nextInt();
if(num>0)
{
System.out.println("The entered number "+num+" is positive.");
}
else
{
System.out.println("The entered number "+num+" is negative.");
}
}
Enter a number: -9
The entered number
-9 is negative.
}
Nested if statement
 The nested if statement represents the if block within another if block.
 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 Program for Nested if else Statement Output
public class code {
public static void main(String[] args) {
int a = 2;
int b = 2;
int c = 2;
if (a == b) {
if (a == c) {
// all are equal
System.out.println("Equal");
} else {
// a!=c
System.out.println("Not equal");
}
} else {
// a!=b
System.out.println("Not equal");
}
}
}
Equal
Java if-else-if ladder Statement
 The if-else-if ladder statement executes one condition from multiple statements.
 Syntax
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Example for IfElseIfExample Output
public class IfElseIfExample {
public static void main(String[] args) {
int marks=65;
if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
else if(marks>=80 && marks<90){
C grade
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}
Java Switch Statement
 The Java switch statement executes one statement from multiple conditions. It is like
if-else-if ladder statement.
 Points to remember
o There can be one or N number of case values for a switch expression.
o The case value must be of switch expression type only. The case value must
be literal or constant. It doesn't allow variables.
o The case values must be unique. In case of duplicate value, it renders compile-
time error.
o Each case statement can have a break statement which is optional.
 Syntax:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
Program for Switch Statement Output
public class SwitchExample {
public static void main(String[] args) {
//Declaring a variable for switch expression
int number=20;
//Switch expression
switch(number){
//Case statements
case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
//Default case statement
20
default:System.out.println("Not in 10, 20 or
30");
}
}
}
Iteration statements (Nov / Dec 2021)
 Iteration statements execute a block of code for several numbers of times until
the condition is true.
while statement
 The while statement is one of the looping constructs control statement that
executes a block of code while a condition is true.
 The loop will stop the execution if the testing expression evaluates to false.
 The loop condition must be a boolean expression.
 Syntax:
while(condition)
{
//code for execution
}
Example Program for while loop Output
public class WhileDemo1
{
public static void main(String[]
args)
{
inti=1;
while(i<=10)
{
System.out.println(i);
i++;
}
}
}
Program for Infinite while loop
public class WhileDemo2
{
public static void main(String[] args)
{
while(true)
{
System.out.println("infinitive while loop");
}
}
}
do-while loop
 In Java, the do-while loop is used to execute statements again and again.
 This loop executes at least once because the loop is executed before the condition is
checked.
 It means loop condition evaluates after executing of loop body.
 The main difference between while and do-while loop is, in do while loop condition
evaluates after executing the loop.
 Syntax:
do
{
//code for execution
}
while(condition);
Example for do while loop Output
public class DoWhileDemo1
{
public static void main(String[] args)
{
inti=1;
do
{
System.out.println(i);
i++;
}while(i<=10);
}
}
Infinite do while Output
public class DoWhileDemo2
{
public static void main(String[] args)
{
do
{
System.out.println("infinitive do while
loop");
}while(true);
}
}
for-each Loop
 In Java, for each loop is used for traversing array or collection elements. In this loop,
there is no need for increment or decrement operator.
Syntax:
for(Type var:array)
{
//code for execution
}
Example:
public class ForEachDemo1
{
public static void main(String[] args)
{
inta[]={20,21,22,23,24};
for(int i:a)
{
System.out.println(i);
}
}
}
Output
For Loop
 The for loop is used for executing a part of the program repeatedly.
 When the number of execution is fixed then it is suggested to use for loop.
 Syntax:
for(initialization;condition;increment/decrement)
{
//statement
}
For loop Parameters:
To create a for loop, we need to set the following parameters.
1) Initialization
It is the initial part, where we set initial value for the loop. It is executed only once at the starting
of loop. It is optional, if we don’t want to set initial value.
2) Condition
It is used to test a condition each time while executing. The execution continues until the
condition is false. It is optional and if we don’t specify, loop will be inifinite.
3) Statement
It is loop body and executed every time until the condition is false.
4) Increment/Decrement
It is used for set increment or decrement value for the loop.
Flowchart
Example Output
public class ForDemo1
{
public static void main(String[] args)
{
int n, i;
n=2;
for(i=1;i<=10;i++)
{
System.out.println(n+"*"+i+"="+n*i);
}
}
}
Nested for loop Output
public class ForDemo2
{
public static void main(String[] args)
{
for(inti=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print("* ");
}
System.out.println();
}
}
}
Break Statement
 In Java, break is a statement that is used to break current execution flow of the program.
 We can use break statement inside loop, switch case etc.
 If break is used inside loop then it will terminate the loop.
 If break is used inside the innermost loop then break will terminate the innermost loop
only and execution will start from the outer loop.
 If break is used in switch case then it will terminate the execution after the matched
case. Use of break, we have covered in our switch case topic.
Example for break statement Output
public class BreakExample {
public static void main(String[] args) {
//using for loop
for(int i=1;i<=10;i++){
1
2
3
4
if(i==5){
//breaking the loop
break;
}
System.out.println(i);
}
}
}
Continue statement
In Java, the continue statement is used to skip the current iteration of the loop. It jumps to
the next iteration of the loop immediately. We can use continue statement with for loop, while
loop and do-while loop as well.
Example for continue statement Output
public class ContinueDemo1
{
public static void main(String[] args)
{
for(inti=1;i<=10;i++)
{
if(i==5)
{
continue;
}
System.out.println(i);
}
}
}
1
2
3
4
5
6
7
8
9
10
Variables
 A variable is an identifier that denotes the storage location.
 Variable is a fundamental unit of storage in Java.
 The variables are used in combination with identifiers, data types, operators and some
value for initialization. The variables must be declared before its use.
 The syntax of variable declaration will be -
data_type name_of_variable [=initialization][,=initialization][,…];
Following are some rules for variable declaration -
 The variable name should not with digits.
 No special character is allowed in identifier except underscore.
 There should not be any blank space with the identifier name.
 The identifier name should not be a keyword.
 The identifier name should be meaningful.
Local Variable in Java
A local variable is a variable which has value within a particular method or a function. Outside
the scope of the function the program has no idea about the variable.
class DataFlair {
int a = 9,
b = 10;
void LearnJava {
int local_j = 45; // A local variable
String s = ”DataFlair Training”; //A local variable
}
}
Java Instance Variable
Instance variables are those which are declared inside the body of a class but not within any
methods.
import java.io. * ;
class Person {
int height,
weight; // Instance Variables
Person(int h, int w) {
this.height = h;
this.weight = w;
}
void run() {
System.out.println(“Huff Puff”);
}
void print() {
System.out.println(“Now my weight is” + this.weight);
}
public static void main(String[] args) throws IOException {
Person A = new Person(170, 65);
A.run();
A.print();
}
}
Output
Huff Puff
Now my weight is 65.
Static Variables in Java
A variable that is declared as static is called a static variable. It cannot be local. You can create
a single copy of the static variable and share it among all the instances of the class. Memory
allocation for static variables happens only once when the class is loaded in the memory.
import java.io. * ;
class DataFlair {
static int studentCount;
DataFlair() {
studentCount = 15;
}
void addStudent() {
studentCount++;
}
public static void main(String[] args) throws IOException {
DataFlair java = new DataFlair();
DataFlair python = new DataFlair();
java.addStudent();
python.addStudent();
System.out.println("Total Students " + studentCount);
}
}
Output:
Total Students 17
Methods
 A method is a block of code or collection of statements or a set of code grouped
together to perform a certain task or operation.
 It is used to achieve the reusability of code.
 We write a method once and use it many times. We do not require to write code again
and again.
Method Declaration
The method declaration provides information about method attributes, such as visibility,
return-type, name, and arguments.
Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. Java
provides four types of access specifier:
 Public: The method is accessible by all classes when we use public specifier in our
application
 Private: When we use a private access specifier, the method is accessible only in the
classes in which it is defined.
 Protected: When we use protected access specifier, the method is accessible within the
same package or subclasses in a different package.
 Default: It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data
type, object, collection, void, etc. If the method does not return anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. Suppose, if
we are creating a method for subtraction of two numbers, the method name must
be subtraction(). A method is invoked by its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left
the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.
Naming a Method
Single-word method name: sum(), area()
Multi-word method name: areaOfCircle(), stringComparision()
Types of Method
There are two types of methods in Java:
o Predefined Method
o User-defined Method
Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries is
known as predefined methods. It is also known as the standard library method or built-in
method.
length(), equals(), compareTo(), sqrt(), etc.
public class Demo
{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
}
}
User-defined Method
The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
//user defined method
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
}
Parameter Passing
• Parameter can be passed to the function by two ways-
1. Call by value
2. Call by reference
• In the call by value method the value of the actual argument is assigned to the formal
parameter. If any change is made in the formal parameter in the subroutine definition then that
change does not reflect the actual parameters.
• Following Java program shows the use of parameter passing by value-
Java Program
//Program implementing the parameter passing by value
public class ParameterByVal
{
void Fun(int a,int b)
{
a=a+5;
b=b+5;
}
public static void main(String args[])
{
ParameterByVal obj1=new ParameterByVal();
int a,b;
a=10;b=20;
System.out.println("The values of a and b before function call");
System.out.println("a= "+a);
System.out.println("b= "+b);
obj1.Fun(a,b);
System.out.println("The values of a and b after function call");
System.out.println("a= "+a);
System.out.println("b= "+b);
}
}
Output
The values of a and b before function call
a= 10
b= 20
The values of a and b after function call
a= 10
b= 20
Java Comments
 The java comments are statements that are not executed by the compiler and interpreter
 The comments can be used to provide information or explanation about the variable,
method, class or any statement.
 It can also be used to hide program code for specific time.
Types of Java Comments
There are 3 types of comments
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
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
*/
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
*
*/
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-name
description
To add a parameter with given name and description to
'Parameters' section.
@return @return description Required for every method that returns something (except void)
Example:
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);
}
}
Structure of Java Program
Documentation Section
The documentation section is an important section but optional for a Java program. It
includes basic information about a Java program. The information includes the author's
name, date of creation, version, program name, company name, and description of the
program.
To write the statements in the documentation section, we use comments. The comments may
be single-line, multi-line, and documentation comments.
Package Declaration
 The package declaration is optional. It is placed just after the documentation section. In
this section, we declare the package name in which the class is placed.
 It must be defined before any class and interface declaration.
 We use the keyword package to declare the package name.
Import statement section
 All the required java API can be imported by the import statement.
 There are some core packages present in the java.
 These packages include the classes and method required for java programming.
 These packages can be imported in the program in order to use the classes and methods
of the program.
Class definition section:
 The class definition section contains the definition of the class. This class normally
contains the data and the methods manipulating the data.
Main method class
 This is called the main method class because it contains the main () function.
 This class can access the methods defined in other classes.
Keywords
Keywords are the reserved words which are enlisted as below-
Difference between constructors and methods
Constructor Methods
Constructor must not have return type. Method must have return type.
Constructor is invoked implicitly. Method is invoked explicitly
The java compiler provides a default
constructor if you don't have any constructor.
Method is not provided by compiler in any
case.
Constructor name must be same as the class
name.
Method name may or may not be same as
class name.

More Related Content

Similar to Object Oriented Programming All Unit Notes

Similar to Object Oriented Programming All Unit Notes (20)

Java OOP Concept
Java OOP ConceptJava OOP Concept
Java OOP Concept
 
Chapter 04 object oriented programming
Chapter 04 object oriented programmingChapter 04 object oriented programming
Chapter 04 object oriented programming
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
javaopps concepts
javaopps conceptsjavaopps concepts
javaopps concepts
 
1 intro
1 intro1 intro
1 intro
 
U1 JAVA.pptx
U1 JAVA.pptxU1 JAVA.pptx
U1 JAVA.pptx
 
M.c.a. (sem iv)- java programming
M.c.a. (sem   iv)- java programmingM.c.a. (sem   iv)- java programming
M.c.a. (sem iv)- java programming
 
Chapter 1- Introduction.ppt
Chapter 1- Introduction.pptChapter 1- Introduction.ppt
Chapter 1- Introduction.ppt
 
Session 02 - Elements of Java Language
Session 02 - Elements of Java LanguageSession 02 - Elements of Java Language
Session 02 - Elements of Java Language
 
INTRODUCTION TO JAVA
INTRODUCTION TO JAVAINTRODUCTION TO JAVA
INTRODUCTION TO JAVA
 
Oop java
Oop javaOop java
Oop java
 
MCA NOTES.pdf
MCA NOTES.pdfMCA NOTES.pdf
MCA NOTES.pdf
 
Principles of OOPs.pptx
Principles of OOPs.pptxPrinciples of OOPs.pptx
Principles of OOPs.pptx
 
Java OOPs Concepts.docx
Java OOPs Concepts.docxJava OOPs Concepts.docx
Java OOPs Concepts.docx
 
Mcs 024 assignment solution (2020-21)
Mcs 024 assignment solution (2020-21)Mcs 024 assignment solution (2020-21)
Mcs 024 assignment solution (2020-21)
 
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language
 
Unit1 jaava
Unit1 jaavaUnit1 jaava
Unit1 jaava
 
Java_Interview Qns
Java_Interview QnsJava_Interview Qns
Java_Interview Qns
 
Java Interview Questions
Java Interview QuestionsJava Interview Questions
Java Interview Questions
 
CS3391 -OOP -UNIT – I NOTES FINAL.pdf
CS3391 -OOP -UNIT – I  NOTES FINAL.pdfCS3391 -OOP -UNIT – I  NOTES FINAL.pdf
CS3391 -OOP -UNIT – I NOTES FINAL.pdf
 

Recently uploaded

Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxvipinkmenon1
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and usesDevarapalliHaritha
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 

Recently uploaded (20)

Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptx
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and uses
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 

Object Oriented Programming All Unit Notes

  • 1. UNIT I INTRODUCTION TO OOP AND JAVA Overview of OOP – Object oriented programming paradigms – Features of Object Oriented Programming – Java Buzzwords – Overview of Java – Data Types, Variables and Arrays – Operators – Control Statements – Programming Structures in Java – Defining classes in Java – Constructors -Methods -Access specifiers - Static members- Java Doc comments Object Oriented Programming Paradigms  The object oriented programming approach is developed in order to remove some of the flaws of procedural programming.  OOP has a complete focus on data and not on the procedures. In OOP, the data can be protected from accidental modification.  In OOP the most important entity called object is created.  Each object consists of data attributes and the methods. The methods or functions operate on data attributes. Difference Between Procedural Programming and Object Oriented Programming (Nov- Dec 2022) Procedure-Oriented Programming Object-Oriented Programming  Divided into  In POP, program is divided into small parts called functions.  In OOP, program is divided into parts called objects.  Importance  In POP, Importance is not given to data but to functions as well as sequence of actions to be done.  In OOP, Importance is given to the data rather than procedures or functions because it works as a real world.  Approach  POP follows Top Down approach.  OOP follows Bottom Up approach.  Access Specifiers  POP does not have any access specifier.  OOP has access specifiers named Public, Private, Protected, etc.  Data Moving  In POP, Data can move freely from function to function in the system.  In OOP, objects can move and communicate with each other through member functions.  Expansion  To add new data and function in POP is not so easy.  OOP provides an easy way to add new data and function.  Data Access  In POP, Most function uses Global data for sharing that can be accessed freely from function to function in the system.  In OOP, data cannot move easily from function to function, it can be
  • 2. kept public or private so we can control the access of data.  Data Hiding  POP does not have any proper way for hiding data so it is less secure.  OOP provides Data Hiding so provides more security.  Overloading  In POP, Overloading is not possible.  In OOP, overloading is possible in the form of Function Overloading and Operator Overloading.  Examples  Example of POP are: C, VB, FORTRAN, Pascal.  Example of OOP are: C++, JAVA, VB.NET, C#.NET. Features of Object Oriented Programming (Nov – Dec 2022) Fundamental principles of OOPS OOPS Concepts  Object o Objects are basic run-time entities in object oriented programming. o Object represent a person, place or any item that a program handles. o A single class can create any number of objects. o Object occupies memory o Every object has data structures called attributes (data) and behaviour called operations (methods/fucntions). o Declaring objects -  The syntax for declaring object is - Class Name Object_Name;  Fruit f1;  For the class Fruit the object f1 can be created.  Classes o A class is a user defined prototype for object creation. o Class does not occupy memory. o In Java, class keyword is used to declare the class. o A class can be defined as an entity in which data and functions are put together. o The concept of class is similar to the concept of structure in C. Syntax : class name_of_class { private: variables declarations; function declarations; public: variable declarations;
  • 3. function declarations; }; do not forget semicolon Difference between class and Objects Object Class  Object is an instance of a class.  Class is a blueprint or template from which objects are created  Object is a real world entity such aspen, laptop, mobile, bed, keyboard, mouse, chair etc  Class is a group of similar objects.  Object is a physical entity.  Class is a logical entity  Object is created through new keyword mainly e.g. Student s1=new Student();  Class is declared using class keyword e.g.class Student{}  Object is created many times as per requirement.  Class is declared once.  Object allocates memory when it is created.  Class doesn't allocated memory when it is created.  Encapsulation o Definition: The wrapping up of data and methods into a single unit is known as encapsulation. o The data inside that class is accessible by the function in the same class. It is normally not accessible from the outside of the component. o This protection mechanism is called data hiding or information hiding.  Abstraction o Definition: Abstraction means representing only essential features by hiding all the implementation details. o In object oriented programming languages like C++, or Java class is an entity used for data abstraction purpose. Example class Student
  • 4. { int roll; char name [10]; public; void input (); void display(); } In main function we can access the functionalities using object. For instance Student obj; obj.input(); obj.display (); Thus only abstract representation can be presented, using class.  Inheritance: o Definition: Inheritance is a property by which the new classes are created using the old classes. In other words the new classes can be developed using some of the properties of old classes. o Inheritance support hierarchical structure. o The old classes are referred as base classes and the new classes are referred as derived classes. That means the derived classes inherit the properties (data and functions) of base class.
  • 5. Example: Here the Shape is a base class from which the Circle, Line and Rectangle are the derived classes. These classes inherit the functionality draw() and resize(). Similarly the Rectangle is a base class for the derived class Square. Along with the derived properties the derived class can have its own properties. For example the class Circle may have the function like backgrcolor() for defining the back ground color.  Polymorphism o Definition: Polymorphism in java is a concept by which we can perform a single action by different ways. o Polymorphism is derived from 2 (two) greek words: poly and morphs. o The word “poly” means many and “morphs” means forms. So, polymorphism means many forms. o Real Time Example:  In a class there will be more students with a same name. We can differentiate the students with their initial, register number etc., Features of Java/ Java Buzzwords/Characteristics of Java  Platform Independent  Object Oriented Concepts  Simple  Secure  Robust  Portable  Multithreading  Distributed Applications  Architectural Neutral Platform Independent:  On compilation Java program is compiled into bytecode.  Byte code is an intermediate code generated from the source code by java compiler and it is platform independent.  This bytecode is platform independent and can be run on any machine, plus this bytecode format also provide security.  Any machine with Java Runtime Environment can run Java Programs.  Java is guaranteed to be write-once, run-anywhere language.
  • 6. Object Oriented  In java, everything is an object which has some data and behaviour. Java can be easily extended as it is based on Object Model. Following are some basic concept of OOP's. o Object o Class o Inheritance o Polymorphism o Abstraction o Encapsulation Simple  Java is very easy to learn, and its syntax is simple, clean and easy to understand.  Java has removed many complicated and rarely-used features, for example, explicit pointers, operator overloading, etc.  There is no need to remove unreferenced objects because there is an Automatic Garbage Collection in Java. Secure  The instructions of bytecode is executed by the Java Virtual Machine (JVM). That means JVM converts the bytecode to machine readable form.  JVM understand only the bytecode and therefore any infectious code cannot be executed by JVM. No virus can infect bytecode. Hence it is difficult to trap the internet and network based applications by the hackers. Robust  Java is robust because: o It uses strong memory management. o There is a lack of pointers that avoids security problems. o Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of objects which are not being used by a Java application anymore. o There are exception handling and the type checking mechanism in Java. Portable  Java program written in one environment can be executed in another environment. Multithreading  Concurrent execution of several parts of same program at the same time.  The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a common memory area. Distributed Applications  This feature is very much useful in networking environment.  In Java, two different objects on different computers can communicate with each other.
  • 7.  This can be achieved by Remote Method Invocation (RMI). Architectural Neutral  Java is architecture neutral because there are no implementation dependent features, for example, the size of primitive types is fixed.  In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit architectures in Java. Operators  Arithmetic Operators  Relational Operators  Logical Operators  Assignment Operators  Bitwise Operators  Unary Operators  Ternary Operator  Instanceof operator
  • 8. Arithmetic operators  Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They act as basic mathematical operations. Operator Description + adds two operands - subtract second operands from first * multiply two operand / divide numerator by denominator % remainder of division ++ Increment operator increases integer value by one -- Decrement operator decreases integer value by one Example program for Arithmetic Operators Output import java.util.Scanner; class Arithmetic_operators1{ public static void main(String args[]) { Scanner in1=new Scanner(System.in); System.out.println("Enter two values"); int a=in1.nextInt(); int b=in1.nextInt(); int c; c=a+b; System.out.println("Addition: "+c); c=a-b; System.out.println("Subtraction: "+c); c=a*b; System.out.println("Multiplication: "+c); c=a/b; System.out.println("Division: "+c); b=3; c=a%b; Enter two values 10 2 Addition: 12 Subtraction: 8 Multiplication: 20 Division: 5 Remainder: 1 Increment Operator: 11 decrement Operator: 10
  • 9. System.out.println("Remainder: "+c); a=++a; System.out.println("Increment Operator: "+a); a=--a; System.out.println("decrement Operator: "+a); } } Relation operators  Relational operators are used to test comparison between operands or values. It can be use to test whether two values are equal or not equal or less than or greater than etc. Operator Description = = Check if two operand are equal != Check if two operand are not equal. > Check if operand on the left is greater than operand on the right < Check operand on the left is smaller than right operand >= check left operand is greater than or equal to right operand <= Check if operand on left is smaller than or equal to right operand Example program for Relational Operators Output import java.util.Scanner; class Arithmetic_operators1{ public static void main(String args[]) { Scanner in1=new Scanner(System.in); System.out.println("Enter two values"); int a=in1.nextInt(); int b=in1.nextInt(); System.out.println("a == b = " + (a == b) ); System.out.println("a != b = " + (a != b) ); System.out.println("a > b = " + (a > b) ); System.out.println("a < b = " + (a < b) ); System.out.println("b >= a = " + (b >= a) ); System.out.println("b <= a = " + (b <= a) ); } } Enter two values 40 30 a == b = false a != b = true a > b = true a < b = false b >= a = false b <= a = true
  • 10. Logical Operators  Logical operators are used to check whether an expression is true or false. Operator Meaning && (Logical AND) true only if both expression1 and expression2 are true || (Logical OR) true if either expression1 or expression2 is true ! (Logical NOT) true if expression is false and vice versa Example program for logical Operators Output class Main { public static void main(String[] args) { // && operator System.out.println((5 > 3) && (8 > 5)); // true System.out.println((5 > 3) && (8 < 5)); // false // || operator System.out.println((5 < 3) || (8 > 5)); // true System.out.println((5 > 3) || (8 < 5)); // true System.out.println((5 < 3) || (8 < 5)); // false // ! operator System.out.println(!(5 == 3)); // true System.out.println(!(5 > 3)); // false } } true false true true false true false Assignment Operators Assignment operators are used in Java to assign values to variables. For example, int age; age = 5; Here, = is the assignment operator. It assigns the value on its right to the variable on its left. That is, 5 is assigned to the variable age. Operator Example Equivalent to = a=b; a=b; += a += b; a = a + b; -= a -= b; a = a - b; *= a *= b; a = a * b; /= a /= b; a = a / b; %= a %= b; a = a % b;
  • 11. Program for Assignment Operators Output public class Assignment{ public static void main(String[] args) { int a = 10; int b=20; int c; System.out.println(c = a); // Output =10 System.out.println(b += a);// Output=30 System.out.println(b -= a);// Output=20 System.out.println(b *= a);// Output=200 System.out.println(b /= a);// Output=20 System.out.println(b %= a);// Output=0 } } 10 30 20 200 20 0 Bitwise operators  Bitwise operators are used to perform operations bit by bit.  Java defines several bitwise operators that can be applied to the integer types long, int, short, char and byte.  The following table shows all bitwise operators supported by Java. Operator Description & Bitwise AND | Bitwise OR ^ Bitwise exclusive OR << left shift >> right shift Now lets see truth table for bitwise &, | and ^ a b a & b a | b a ^ b 0 0 0 0 0 0 1 0 1 1
  • 12. 1 0 0 1 1 1 1 1 1 0 The bitwise shift operators shifts the bit value. The left operand specifies the value to be shifted and the right operand specifies the number of positions that the bits in the value are to be shifted. Both operands have the same precedence. Program for Bitwise Operators Output public class Main{ public static void main(String[] args) { int a=4, b=3; System.out.println(a&b); System.out.println(a|b); System.out.println(a^b); System.out.println(a<<2); System.out.println(a>>2); System.out.println(~a); } } 0 7 7 16 1 -5 Unary Operator Incrementing/decrementing a value by one Java also provides increment and decrement operators: ++ and -- respectively. ++ increases the value of the operand by 1, while -- decrease it by 1. 1. public class OperatorExample{ 2. public static void main(String args[]){ 3. int x=10; 4. System.out.println(x++);//10 (11) 5. System.out.println(++x);//12 6. System.out.println(x--);//12 (11) 7. System.out.println(--x);//10 8. }} 10 12 12 10 Java Ternary Operator/ Conditional Operator  The ternary operator (conditional operator) is shorthand for the if-then-else statement. For example,  variable = Expression ? expression1 : expression2
  • 13. Here's how it works.  If the Expression is true, expression1 is assigned to the variable.  If the Expression is false, expression2 is assigned to the variable. Example for Ternary Operator Output class Java { public static void main(String[] args) { int februaryDays = 29; String result; // ternary operator result = (februaryDays == 28) ? "Not a leap year" : "Leap year"; System.out.println(result); } } Leap year Java instanceof Operator  The instanceof operator checks whether an object is an instanceof a particular class. Example for Ternary Operator Output class Main { public static void main(String[] args) { String str = "Akshaya"; boolean result; // checks if str is an instance of // the String class result = str instanceof String; System.out.println("Is str an object of String? " + result); } } Is str an object of String? true Arrays  An array is a collection of similar data types.  Array is a container object that hold values of homogeneous type. It is also known as static data structure because size of an array must be specified at the time of its declaration.  Array starts from zero index and goes to n-1 where n is length of the array.  Each element in the array can be accessed by using the index number.  In java array is an Object.  There are two types of arrays – o One dimensional arrays o Two dimensional arrays  One Dimensional Array
  • 14. o Represented using single index o The syntax of declaring array is –  data_type array_name[ ]; o and to allocate the memory –  array_name=new data_type[size]; o We can combine both declaration and initialization in a single statement.  Datatype[] arrayName = new datatype[size] Initializing All Array Elements to Zero Output public class InitializeDemo { public static void main(String[] args) { //Declaring array int[] intArray; //Initializing to Zero intArray = new int[5]; //Printing the values for(int i = 0; i < intArray.length; i++) System.out.println(intArray[i]); } } 0 0 0 0 0 For string array the default value is null Output public class InitializeDemo { public static void main(String[] args) { //Declaring array String[] strArray; //Initializing to Zero strArray = new String[5]; //Printing the values for(int i = 0; i < strArray.length; i++) System.out.println(strArray[i]); } } null null null null null Program to take user input to initialize an array by using the Scanner class Output import java.util.Scanner; public class InitializeDemo { public static void main(String[] args) { //Declaring array int[] intArray; //Defining the array length intArray = new int[5]; Enter the values: 5 10 15 20 25 The array contains: 5 10 15
  • 15. Scanner s = new Scanner(System.in); System.out.println("Enter the values: "); //Initializing for(int i = 0; i < intArray.length; i++) intArray[i] = s.nextInt(); s.close(); System.out.println("The array contains: "); //Printing the values for(int i = 0; i < intArray.length; i++) System.out.println(intArray[i]); } } 20 25 Initializing an Array at the time Declaration Output public class InitializeDemo { public static void main(String[] args) { //Declaring array int[] intArray = {3,6,9,12,15}; //Printing the values for(int i = 0; i < intArray.length; i++) System.out.println(intArray[i]); } } 3 6 9 12 15 Two – dimensional Array (2D-Array)  Two – dimensional array is the simplest form of a multidimensional array.  Two Dimensional Array can be represented as the collection of rows and columns.  Declaration – Syntax: o data_type[][] array_name = new data_type[x][y];  Initialization – Syntax: o array_name[row_index][column_index] = value; o For example: arr[0][0] = 1;  Direct Method of Declaration: Syntax: o data_type[][] array_name = { {valueR1C1, valueR1C2, ....}, {valueR2C1, valueR2C2, ....} };
  • 16. Java program that takes a two-dimensional array as input. Output import java.util.Scanner; public class ArrayInputExample2 { public static void main(String args[]) { int m, n, i, j; Scanner sc=new Scanner(System.in); System.out.print("Enter the number of rows: "); //taking row as input m = sc.nextInt(); System.out.print("Enter the number of columns: "); //taking column as input n = sc.nextInt(); // Declaring the two-dimensional matrix int array[][] = new int[m][n]; // Read the matrix values System.out.println("Enter the elements of the array: "); //loop for row for (i = 0; i < m; i++) //inner for loop for column for (j = 0; j < n; j++) array[i][j] = sc.nextInt(); //accessing array elements System.out.println("Elements of the array are: "); for (i = 0; i < m; i++) { for (j = 0; j < n; j++)
  • 17. //prints the array elements System.out.print(array[i][j] + " "); //throws the cursor to the next line System.out.println(); } } } Program for direct method of declaration Output import java.io.*; class GFG { public static void main(String[] args) { int[][] arr = { { 1, 2 }, { 3, 4 } }; for (int i = 0; i < 2; i++) for (int j = 0; j < 2; j++) System.out.println("arr[" + i + "][" + j + "] = "+ arr[i][j]); } } arr[0][0] = 1 arr[0][1] = 2 arr[1][0] = 3 arr[1][1] = 4 Accessing elements of Two Dimensional Array Output import java.io.*; class GFG { public static void main(String[] args) { int[][] arr = { { 1, 2 }, { 3, 4 } }; System.out.println("arr[0][0] = " + arr[0][0]); } } arr[0][0] = 1 Constructors (Nov/Dec 2022)  Definition: The constructor is a specialized method for initializing objects.  Name of the constructor is same as that of its class name. In other words, the name of the constructor and class name is same.
  • 18.  Whenever an object of its associated class is created, the constructor is invoked automatically.  The constructor is called constructor because it creates values for data fields of class. Program for Default and parameterised constructor Output public class Rectangle 1 { int height; int width; Rectangle1() { System.out.println(" Simple constructor: values are initialised..."); height=10; width=20; } Rectangle1 (int h,int w) { System.out.println(" Parameterised constructor: values are initialised..."); height=h; width=w; } void area() { System.out.println("Now, The function is called..."); F:test>javac Rectangle1.java F:test>java Constr_Demo Simple constructor: values are initialised... Now, The function is called... The area is 200 Parameterised constructor: values are initialised... Now, The function is called... The area is 220 F:test> Data fields Simple constructor Parameterized constructor Method defined
  • 19. int result height*width; System.out.println("The area is "+result); } class Constr_Demo { public static void main(String args[]) { Rectangle1 obj = new Rectangle 1(); obj.area();//call the to method Rectangle1 obj1 = new Rectangle 1(11,20); obj1.area();//call the to method } } Properties of constructor  Name of constructor must be the same as the name of the class for which it is being used.  The constructor must be declared in the public mode.  The constructor gets invoked automatically when an object gets created.  The constructor should not have any return type. Even a void data type should not be written for the constructor.  The constructor cannot be used as a member of union or structure.  The constructors can have default arguments.  The constructor cannot be inherited.  Constructor can make use of new or delete operators for allocating or releasing memory respectively.  Constructor cannot be virtual.  Multiple constructors can be used by the same class.  When we declare the constructor explicitly then we must declare the object of that class. Defining classes in Java Defining a class  A class is a group of objects which have common properties.  It is a template or blueprint from which objects are created.  It is a logical entity. Object created and simple constructor is invoked Object created and parameterized constructor is invoked
  • 20.  It can’t be physical.  A class in Java can contain: o Fields o Methods o Constructors o Blocks o Nested class and interface Syntax to declare a class: class <class_name>{ field; method; } Instance variable in Java o A variable which is created inside the class but outside the method is known as an instance variable. o Instance variable doesn't get memory at compile time. o It gets memory at runtime when an object or instance is created. o That is why it is known as an instance variable. Object and Class Example: main within the class Here, we are creating a main() method inside the class. Java Program to illustrate how to define a class and fields Output 1. class Student{ int id; 1. String name; public static void main(String args[]){ Student s1=new Student(); System.out.println(s1.id); System.out.println(s1.name); } } 0 null Object and Class Example: main outside the class o In real time development, we create classes and use it from another class. o It is a better approach than previous one. o Let's see a simple example, where we are having main () method in another class. Java Program to demonstrate having the main method in another class Output class Student{ int id; String name; 0 null
  • 21. } class TestStudent1{ public static void main(String args[]){ Student s1=new Student(); System.out.println(s1.id); System.out.println(s1.name); } } 3 Ways to initialize object There are 3 ways to initialize object in Java. o By reference variable o By method o By constructor 1) Object and Class Example: Initialization through reference Initializing an object means storing data into the object. Let's see a simple example where we are going to initialize the object through a reference variable. Object and Class Example: Initialization through reference Output class Student{ int id; String name; } class TestStudent2{ public static void main(String args[]){ Student s1=new Student(); s1.id=101; s1.name="Akshaya"; System.out.println(s1.id+" "+s1.name); } } 101 Akshaya 2) Object and Class Example: Initialization through method In this example, we are creating the two objects of Student class and initializing the value to these objects by invoking the insertRecord method. Object and Class Example: Initialization through method Output class Student{ int rollno; String name; void insertRecord(int r, String n){ rollno=r; name=n; } void displayInformation(){System.out.println(rollno+" "+name);} 111 Karan 222 Aryan
  • 22. } class TestStudent4{ public static void main(String args[]){ Student s1=new Student(); Student s2=new Student(); s1.insertRecord(111,"Karan"); s2.insertRecord(222,"Aryan"); s1.displayInformation(); s2.displayInformation(); } } As you can see in the above figure, object gets the memory in heap memory area. The reference variable refers to the object allocated in the heap memory area. Here, s1 and s2 both are reference variables that refer to the objects allocated in memory. Object and Class Example: Initialization through a constructor Object and Class Example: Initialization through a constructor Output class Employee{ int id; String name; float salary; void insert(int i, String n, float s) { id=i; name=n; salary=s; } 101 ajeet 45000.0 102 irfan 25000.0 103 nakul 55000.0
  • 23. void display(){System.out.println(id+" "+name+" "+salary);} } public class TestEmployee { public static void main(String[] args) { Employee e1=new Employee(); Employee e2=new Employee(); Employee e3=new Employee(); e1.insert(101,"ajeet",45000); e2.insert(102,"irfan",25000); e3.insert(103,"nakul",55000); e1.display(); e2.display(); e3.display(); } } Object & Class Example: Rectangle Output class Rectangle{ int length; int width; void insert(int l,int w){ length=l; width=w; } void calculateArea(){System.out.println(length*width);} } class TestRectangle2{ public static void main(String args[]){ Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects r1.insert(11,5); r2.insert(3,15); r1.calculateArea(); r2.calculateArea(); } } 55 45 Access Specifiers  Access modifiers control access to data fields, methods, and classes. There are three modifiers used in Java –  public  private  default modifier  public allows classes, methods and data fields accessible from any class
  • 24.  private allows classes, methods and data fields accessible only from within the own class.  If public or private is not used then by default the classes, methods, data fields are assessable by any class in the same package. This is called package-private or package- access. A package is essentially grouping of classes. Example program to demonstrate the usage of access specifiers. package Test; public class class1 { public int a; int b; private int c; public void fun1() { } void fun2() { } private void fun3() { } } public class class2 { void My_method() { class 1 obj=new class1(); obj.a;//allowed obj.b;//allowed obj.c;//error:cannot access obj.fun1();//allowed package another Test public class class3 { void My_method() class1 obj=new class1(); obj.a;//allowed obj.b;// error:cannot access obj.c;//error:cannot access obj.fun1();//allowed obj.fun2()//error:cannot access obj.fun3()//error:cannot access } }
  • 25. obj.fun2();//allowed obj.fun3();//error:cannot access } }  Protected mode is another access specifier which is used in inheritance.  The protected mode allows accessing the members to all the classes and subclasses in the same package as well as to the subclasses in other package.  But the non subclasses in other package cannot access the protected members. The effect of access specifiers for class, subclass or package is enlisted below- Static Members  The static members can be static data member or static method.  The static members are those members which can be accessed without using object. Program to introduce the use of the static method and static variables Output class StaticProg { static int a = 10; static void fun(int b) { System.out.println("b= "+b); System.out.println("a = "+a); } } class AnotherClass a= 10 b= 20 a= 10
  • 26. { public static void main(String[] args) { System.out.println("a= "+Static Prog.a); StaticProg.fun(20); } } Program Explanation In above program, we have declared one static variable a and a static member function fun(). These static members are declared in one class StaticProg. Then we have written one more class in which the main method is defined. This class is named as AnotherClass. From this class the static members of class StaticProg are accessed without using any object. Syntax: ClassName.staticMember Points to Remember  In Java the main is always static method.  The static methods must can access only static data.  The static method can call only the static method and cannot call a non-static method.  The static method cannot refer to this pointer.  The static method cannot refer to super method. Java Data types (Nov/Dec 2021)  Java is a statically typed and also a strongly typed language.  In Java, each type of data (such as integer, character, hexadecimal, etc. ) is predefined as part of the programming language and all constants or variables defined within a given program must be described with one of the data types Data types represent the different values to be stored in the variable. In java, there are two categories of data types:  Primitive data types  Non-primitive data types
  • 27. The Primitive Types Java defines eight primitive types of data: byte, short, int, long, char, float, double, and boolean. 1. Integers  This group includes byte, short, int, and long.  All of these are signed, positive and negative values. Name Width in bits Range long 64 –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 int 32 –2,147,483,648 to 2,147,483,647 short 16 –32,768 to 32,767 byte 8 –128 to 127 2. Float-point numbers:  They are also known as real numbers.  This group includes float and double, which represents single- and double- precision numbers, respectively. Name Width in bits Range double 64 4.9e–324 to 1.8e+308 float 32 1.4e–045 to 3.4e+038 3. Characters - This group includes char, which represents symbols in a character set like letters and numbers. Char is 16-bit type. The range of a char is 0 to 65,536. 4. Boolean: This group includes boolean. It can have only one of two possible values, true or false. This program introduces use of various data type in the program Output class DatatypeDemo { public static void main(String args[]) { The value of a=: 10 The value of b=: 1280 The value of c=: 1280000 The value of d=: 1280000000
  • 28. byte a=10; short b=10*128; int c=10000* 128; long d=10000*1000*128; double e=99.9998; char f='a'; boolean g=true; boolean h=false; dynamic initialization System.out.println("The value of a=: "+a); System.out.println("The value of b=: "+b); System.out.println("The value of c=: "+c); System.out.println("The value of d=: "+d); System.out.println("The value of e=: "+e); System.out.println("The value of f=: "+f); f++; System.out.println("The value of f after increment=: "+f); System.out.println("The value of g=: "+g); System.out.println("The value of h=: "+h); } } The value of e=: 99.9998 The value of f=: a The value of f after increment=: b The value of g=: true The value of h=: false Control Statements (Nov/Dec 2020)  Control statements in Java is one of the fundamentals required for Java Programming.  It allows the smooth flow of a program.  Control Statements are divided into three categories, namely o Selection statements/ Decision making statements o Iteration Statements/ Looping Statements Selection Statements  Simple if statement  if else statement  nested if statement  if-else-if ladder  Switch statement Simple 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 be executed.  Syntax: if(<conditional expression>)
  • 29. { < Statement Action> } //Java Program for implementation of if statement Output import java.util.Scanner; public class Main { public static void main(String []args) { //Take input from the user //Create an instance of the Scanner class Scanner sc=new Scanner(System.in); System.out.println("Enter the age: "); int age=sc.nextInt(); if(age>=18) { System.out.println("The person is eligible to vote"); } } } Enter the age: 21 The person is eligible to vote if-else statement  The if-else statement is used for testing condition. If the condition is true, if block executes otherwise else block executes.  The else block execute only when condition is false.
  • 30. Syntax: if(<conditional expression>) { < Statement Action1> } else { < Statement Action2> } //Java Program for implementation of if-else statement Output import java.util.Scanner; public class Main { public static void main(String []args) { //Take input from the user //Create an instance of the Scanner class Scanner sc=new Scanner(System.in); System.out.println("Enter a number: "); int num=sc.nextInt(); if(num>0) { System.out.println("The entered number "+num+" is positive."); } else { System.out.println("The entered number "+num+" is negative."); } } Enter a number: -9 The entered number -9 is negative.
  • 31. } Nested if statement  The nested if statement represents the if block within another if block.  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 Program for Nested if else Statement Output public class code { public static void main(String[] args) { int a = 2; int b = 2; int c = 2; if (a == b) { if (a == c) { // all are equal System.out.println("Equal"); } else { // a!=c System.out.println("Not equal"); } } else { // a!=b System.out.println("Not equal"); } } } Equal
  • 32. Java if-else-if ladder Statement  The if-else-if ladder statement executes one condition from multiple statements.  Syntax if(condition1){ //code to be executed if condition1 is true }else if(condition2){ //code to be executed if condition2 is true } else if(condition3){ //code to be executed if condition3 is true
  • 33. } ... else{ //code to be executed if all the conditions are false } Example for IfElseIfExample Output public class IfElseIfExample { public static void main(String[] args) { int marks=65; if(marks<50){ System.out.println("fail"); } else if(marks>=50 && marks<60){ System.out.println("D grade"); } else if(marks>=60 && marks<70){ System.out.println("C grade"); } else if(marks>=70 && marks<80){ System.out.println("B grade"); } else if(marks>=80 && marks<90){ C grade
  • 34. System.out.println("A grade"); }else if(marks>=90 && marks<100){ System.out.println("A+ grade"); }else{ System.out.println("Invalid!"); } } } Java Switch Statement  The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement.  Points to remember o There can be one or N number of case values for a switch expression. o The case value must be of switch expression type only. The case value must be literal or constant. It doesn't allow variables. o The case values must be unique. In case of duplicate value, it renders compile- time error. o Each case statement can have a break statement which is optional.  Syntax: switch(expression){ case value1: //code to be executed; break; //optional case value2: //code to be executed; break; //optional ...... default: code to be executed if all cases are not matched; } Program for Switch Statement Output public class SwitchExample { public static void main(String[] args) { //Declaring a variable for switch expression int number=20; //Switch expression switch(number){ //Case statements case 10: System.out.println("10"); break; case 20: System.out.println("20"); break; case 30: System.out.println("30"); break; //Default case statement 20
  • 35. default:System.out.println("Not in 10, 20 or 30"); } } } Iteration statements (Nov / Dec 2021)  Iteration statements execute a block of code for several numbers of times until the condition is true. while statement  The while statement is one of the looping constructs control statement that executes a block of code while a condition is true.  The loop will stop the execution if the testing expression evaluates to false.  The loop condition must be a boolean expression.  Syntax: while(condition) {
  • 36. //code for execution } Example Program for while loop Output public class WhileDemo1 { public static void main(String[] args) { inti=1; while(i<=10) { System.out.println(i); i++; } } }
  • 37. Program for Infinite while loop public class WhileDemo2 { public static void main(String[] args) { while(true) { System.out.println("infinitive while loop"); } } } do-while loop  In Java, the do-while loop is used to execute statements again and again.  This loop executes at least once because the loop is executed before the condition is checked.  It means loop condition evaluates after executing of loop body.  The main difference between while and do-while loop is, in do while loop condition evaluates after executing the loop.  Syntax: do { //code for execution } while(condition);
  • 38. Example for do while loop Output public class DoWhileDemo1 { public static void main(String[] args) { inti=1; do { System.out.println(i); i++; }while(i<=10); } } Infinite do while Output public class DoWhileDemo2 { public static void main(String[] args) { do { System.out.println("infinitive do while loop"); }while(true); } } for-each Loop  In Java, for each loop is used for traversing array or collection elements. In this loop, there is no need for increment or decrement operator. Syntax: for(Type var:array) { //code for execution } Example: public class ForEachDemo1
  • 39. { public static void main(String[] args) { inta[]={20,21,22,23,24}; for(int i:a) { System.out.println(i); } } } Output For Loop  The for loop is used for executing a part of the program repeatedly.  When the number of execution is fixed then it is suggested to use for loop.  Syntax: for(initialization;condition;increment/decrement) { //statement } For loop Parameters: To create a for loop, we need to set the following parameters.
  • 40. 1) Initialization It is the initial part, where we set initial value for the loop. It is executed only once at the starting of loop. It is optional, if we don’t want to set initial value. 2) Condition It is used to test a condition each time while executing. The execution continues until the condition is false. It is optional and if we don’t specify, loop will be inifinite. 3) Statement It is loop body and executed every time until the condition is false. 4) Increment/Decrement It is used for set increment or decrement value for the loop. Flowchart
  • 41. Example Output public class ForDemo1 { public static void main(String[] args) { int n, i; n=2; for(i=1;i<=10;i++) { System.out.println(n+"*"+i+"="+n*i); } } } Nested for loop Output public class ForDemo2 { public static void main(String[] args) { for(inti=1;i<=5;i++) { for(int j=1;j<=i;j++) { System.out.print("* "); } System.out.println(); } } } Break Statement  In Java, break is a statement that is used to break current execution flow of the program.  We can use break statement inside loop, switch case etc.  If break is used inside loop then it will terminate the loop.  If break is used inside the innermost loop then break will terminate the innermost loop only and execution will start from the outer loop.  If break is used in switch case then it will terminate the execution after the matched case. Use of break, we have covered in our switch case topic. Example for break statement Output public class BreakExample { public static void main(String[] args) { //using for loop for(int i=1;i<=10;i++){ 1 2 3 4
  • 42. if(i==5){ //breaking the loop break; } System.out.println(i); } } } Continue statement In Java, the continue statement is used to skip the current iteration of the loop. It jumps to the next iteration of the loop immediately. We can use continue statement with for loop, while loop and do-while loop as well. Example for continue statement Output public class ContinueDemo1 { public static void main(String[] args) { for(inti=1;i<=10;i++) { if(i==5) { continue; } System.out.println(i); } } } 1 2 3 4 5 6 7 8 9 10 Variables  A variable is an identifier that denotes the storage location.  Variable is a fundamental unit of storage in Java.  The variables are used in combination with identifiers, data types, operators and some value for initialization. The variables must be declared before its use.  The syntax of variable declaration will be - data_type name_of_variable [=initialization][,=initialization][,…]; Following are some rules for variable declaration -  The variable name should not with digits.  No special character is allowed in identifier except underscore.  There should not be any blank space with the identifier name.  The identifier name should not be a keyword.  The identifier name should be meaningful.
  • 43. Local Variable in Java A local variable is a variable which has value within a particular method or a function. Outside the scope of the function the program has no idea about the variable. class DataFlair { int a = 9, b = 10; void LearnJava { int local_j = 45; // A local variable String s = ”DataFlair Training”; //A local variable } } Java Instance Variable Instance variables are those which are declared inside the body of a class but not within any methods. import java.io. * ; class Person { int height, weight; // Instance Variables Person(int h, int w) { this.height = h; this.weight = w; } void run() { System.out.println(“Huff Puff”); } void print() { System.out.println(“Now my weight is” + this.weight); } public static void main(String[] args) throws IOException { Person A = new Person(170, 65); A.run(); A.print(); } } Output Huff Puff Now my weight is 65.
  • 44. Static Variables in Java A variable that is declared as static is called a static variable. It cannot be local. You can create a single copy of the static variable and share it among all the instances of the class. Memory allocation for static variables happens only once when the class is loaded in the memory. import java.io. * ; class DataFlair { static int studentCount; DataFlair() { studentCount = 15; } void addStudent() { studentCount++; } public static void main(String[] args) throws IOException { DataFlair java = new DataFlair(); DataFlair python = new DataFlair(); java.addStudent(); python.addStudent(); System.out.println("Total Students " + studentCount); } } Output: Total Students 17 Methods  A method is a block of code or collection of statements or a set of code grouped together to perform a certain task or operation.  It is used to achieve the reusability of code.  We write a method once and use it many times. We do not require to write code again and again. Method Declaration The method declaration provides information about method attributes, such as visibility, return-type, name, and arguments.
  • 45. Method Signature: Every method has a method signature. It is a part of the method declaration. It includes the method name and parameter list. Access Specifier: Access specifier or modifier is the access type of the method. Java provides four types of access specifier:  Public: The method is accessible by all classes when we use public specifier in our application  Private: When we use a private access specifier, the method is accessible only in the classes in which it is defined.  Protected: When we use protected access specifier, the method is accessible within the same package or subclasses in a different package.  Default: It is visible only from the same package only. Return Type: Return type is a data type that the method returns. It may have a primitive data type, object, collection, void, etc. If the method does not return anything, we use void keyword. Method Name: It is a unique name that is used to define the name of a method. Suppose, if we are creating a method for subtraction of two numbers, the method name must be subtraction(). A method is invoked by its name. Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of parentheses. It contains the data type and variable name. If the method has no parameter, left the parentheses blank. Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is enclosed within the pair of curly braces. Naming a Method Single-word method name: sum(), area() Multi-word method name: areaOfCircle(), stringComparision() Types of Method There are two types of methods in Java: o Predefined Method o User-defined Method
  • 46. Predefined Method In Java, predefined methods are the method that is already defined in the Java class libraries is known as predefined methods. It is also known as the standard library method or built-in method. length(), equals(), compareTo(), sqrt(), etc. public class Demo { public static void main(String[] args) { // using the max() method of Math class System.out.print("The maximum number is: " + Math.max(9,7)); } } User-defined Method The method written by the user or programmer is known as a user-defined method. These methods are modified according to the requirement. import java.util.Scanner; public class EvenOdd { public static void main (String args[]) { //creating Scanner class object Scanner scan=new Scanner(System.in); System.out.print("Enter the number: "); //reading value from user int num=scan.nextInt(); //method calling findEvenOdd(num); } //user defined method public static void findEvenOdd(int num) { //method body
  • 47. if(num%2==0) System.out.println(num+" is even"); else System.out.println(num+" is odd"); } } Parameter Passing • Parameter can be passed to the function by two ways- 1. Call by value 2. Call by reference • In the call by value method the value of the actual argument is assigned to the formal parameter. If any change is made in the formal parameter in the subroutine definition then that change does not reflect the actual parameters. • Following Java program shows the use of parameter passing by value- Java Program //Program implementing the parameter passing by value public class ParameterByVal { void Fun(int a,int b) { a=a+5; b=b+5; } public static void main(String args[])
  • 48. { ParameterByVal obj1=new ParameterByVal(); int a,b; a=10;b=20; System.out.println("The values of a and b before function call"); System.out.println("a= "+a); System.out.println("b= "+b); obj1.Fun(a,b); System.out.println("The values of a and b after function call"); System.out.println("a= "+a); System.out.println("b= "+b); } } Output The values of a and b before function call a= 10 b= 20 The values of a and b after function call a= 10 b= 20
  • 49. Java Comments  The java comments are statements that are not executed by the compiler and interpreter  The comments can be used to provide information or explanation about the variable, method, class or any statement.  It can also be used to hide program code for specific time. Types of Java Comments There are 3 types of comments 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
  • 50. 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 */ 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 * */ 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.
  • 51. @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-name description To add a parameter with given name and description to 'Parameters' section. @return @return description Required for every method that returns something (except void) Example: 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.
  • 52. * @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); } } Structure of Java Program Documentation Section The documentation section is an important section but optional for a Java program. It includes basic information about a Java program. The information includes the author's
  • 53. name, date of creation, version, program name, company name, and description of the program. To write the statements in the documentation section, we use comments. The comments may be single-line, multi-line, and documentation comments. Package Declaration  The package declaration is optional. It is placed just after the documentation section. In this section, we declare the package name in which the class is placed.  It must be defined before any class and interface declaration.  We use the keyword package to declare the package name. Import statement section  All the required java API can be imported by the import statement.  There are some core packages present in the java.  These packages include the classes and method required for java programming.  These packages can be imported in the program in order to use the classes and methods of the program. Class definition section:  The class definition section contains the definition of the class. This class normally contains the data and the methods manipulating the data. Main method class  This is called the main method class because it contains the main () function.  This class can access the methods defined in other classes. Keywords Keywords are the reserved words which are enlisted as below-
  • 54. Difference between constructors and methods Constructor Methods Constructor must not have return type. Method must have return type. Constructor is invoked implicitly. Method is invoked explicitly The java compiler provides a default constructor if you don't have any constructor. Method is not provided by compiler in any case. Constructor name must be same as the class name. Method name may or may not be same as class name.