0% found this document useful (0 votes)
46 views142 pages

Java OOP Concepts and Basics Guide

This document provides an introduction to Object-Oriented Programming (OOP) concepts and Java programming basics, including data types, variables, operators, and control structures. It covers key OOP principles such as encapsulation, inheritance, polymorphism, and abstraction, along with Java's primitive and non-primitive data types, variable types, and various operators. Additionally, it includes examples to illustrate Java syntax and functionality.

Uploaded by

hlshreeshanthi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views142 pages

Java OOP Concepts and Basics Guide

This document provides an introduction to Object-Oriented Programming (OOP) concepts and Java programming basics, including data types, variables, operators, and control structures. It covers key OOP principles such as encapsulation, inheritance, polymorphism, and abstraction, along with Java's primitive and non-primitive data types, variable types, and various operators. Additionally, it includes examples to illustrate Java syntax and functionality.

Uploaded by

hlshreeshanthi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Unit1:

Introduction
Unit1
Introductions to oops and java
• Oops concepts and paradigm
• Basics of java programming
• Data types
• Variables
• Operators
• Control structures
• Method overloading
• Math class
• Arrays in java
Oops Concepts And Paradigm:

Object-Oriented Programming is a paradigm that provides many concepts, such


as inheritance, data binding, polymorphism, etc.

Simula is considered the first object-oriented programming language. The programming


paradigm where everything is represented as an object is known as a truly object-oriented
programming language.

Smalltalk is considered the first truly object-oriented programming language.

The popular object-oriented languages are Java, C#, PHP, Python, C++, etc.
The main aim of object-oriented programming is to implement real-world entities, for
example, object, classes, abstraction, inheritance, polymorphism, etc.
Object:
Any entity that has state and behavior is known as an object.
For example, a chair, pen, table, keyboard, bike, etc. It can be
physical or logical.

An Object can be defined as an instance of a class. An object


contains an address and takes up some space in memory.
Objects can communicate without knowing the details of each
other's data or code. The only necessary thing is the type of
message accepted and the type of response returned by the
objects.

Example: A dog is an object because it has states like color,


name, breed, etc. as well as behaviors like wagging the tail,
barking, eating, etc.
Class

Collection of objects is called class. It is a logical


entity.

A class can also be defined as a blueprint from


which you can create an individual object. Class
doesn't consume any space.
Encapsulation

Binding (or wrapping) code and data together into


a single unit are known as encapsulation. For
example, a capsule, it is wrapped with different
medicines.

A java class is the example of encapsulation. Java


bean is the fully encapsulated class because all the
data members are private here.
Polymorphism

If one task is performed in different ways, it is


known as polymorphism. For example: to
convince the customer differently, to draw
something, for example, shape, triangle,
rectangle, etc.

In Java, we use method overloading and method


overriding to achieve polymorphism.
Another example can be to speak something; for
example, a cat speaks meow, dog barks woof, etc.
Inheritance

When one object acquires all the properties and


behaviors of a parent object, it is known as
inheritance. It provides code reusability. It is
used to achieve runtime polymorphism.

Inheritance is a mechanism of driving a new


class from an existing class. The existing (old)
class is known as base class or super
class or parent class. The new class is known
as a derived class or sub class or child class. It
allows us to use the properties and behavior of
one class (parent) in another class (child).
Single level inheritance

In single inheritance, a sub-class is derived from


only one super class. It inherits the properties and
behavior of a single-parent class. Sometimes it is
also known as simple inheritance.
Multiple inheritance
.

Multiple Inheritance is a feature of C++ where a


class can inherit from more than one classes.
The constructors of inherited classes are called in
the same order in which they are inherited.
For example, in the following program, B’s
constructor is called before A’s constructor.
Multilevel inheritance

In multi-level inheritance, a class is derived


from a class which is also derived from
another class is called multi-level inheritance.
In simple words, we can say that a class that
has more than one parent class is called
multi-level inheritance. Note that the classes
must be at different levels.
Hence, there exists a single base class and
single derived class but multiple intermediate
base classes.
Hierarchical Inheritance

If a number of classes are derived from a


single base class, it is called hierarchical
inheritance
Hybrid inheritance

Hybrid means consist of more than one. Hybrid


inheritance is the combination of two or more
types of inheritance.
Abstraction

Hiding internal details and showing


functionality is known as abstraction.

For example phone call, we don't know


the internal processing.
Basics of Java Programming:
Data Types:
Data types specify the different sizes and values that can be stored in the variable. There
are two types of data types in Java:

[Link] data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.

[Link]-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.
Java Primitive Data Types

In Java language, primitive data types are the building blocks of data manipulation. These
are the most basic data types available in Java language.

There are 8 types of primitive data types:


•boolean data type
•byte data type
•char data type
•short data type
•int data type
•long data type
•float data type
•double data type
Boolean Data Type

The Boolean data type is used to store only two possible values: true and false. This data
type is used for simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.

Example:
[Link] one = false
Byte Data Type

The byte data type is an example of primitive data type. It isan 8-bit signed two's
complement integer. Its value-range lies between -128 to 127 (inclusive). Its minimum
value is -128 and maximum value is 127. Its default value is 0.

The byte data type is used to save memory in large arrays where the memory savings is
most required. It saves space because a byte is 4 times smaller than an integer. It can also
be used in place of "int" data type.

Example:
byte a = 10, byte b = -20
Short Data Type

The short data type is a 16-bit signed two's complement integer. Its value-range lies
between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum
value is 32,767. Its default value is 0.

The short data type can also be used to save memory just like byte data type. A short data
type is 2 times smaller than an integer.

Example:
[Link] s = 10000, short r = -5000
Int Data Type

The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is -
2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.

The int data type is generally used as a default data type for integral values unless if there is
no problem about memory.

Example:
[Link] a = 100000, int b = -200000
Long Data Type

The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive).
Its minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807.
Its default value is 0. The long data type is used when you need a range of values more than
those provided by int.

Example:
[Link] a = 100000L, long b = -200000L
Float Data Type

The float data type is a single-precision 32-bit IEEE 754 floating [Link] value range is
unlimited. It is recommended to use a float (instead of double) if you need to save memory
in large arrays of floating point numbers.
The float data type should never be used for precise values, such as currency. Its default
value is 0.0F.

Example:
float f1 = 234.5f
Double Data Type

The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range
is unlimited. The double data type is generally used for decimal values just like float. The
double data type also should never be used for precise values, such as currency. Its default
value is 0.0d.

Example:
[Link] d1 = 12.3
Char Data Type

The char data type is a single 16-bit Unicode character. Its value-range lies between '\
u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.

Example:
[Link] letterA = 'A'
Variables:
A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type.
Variable is a name of memory location. There are three types of variables in java: local,
instance and static.

There are two types of data types in Java: primitive and non-primitive.

Variable
A variable is the name of a reserved area allocated in memory. In other words, it is a name
of the memory location. It is a combination of "vary + able" which means its value can be
changed.
[Link] data=50;//Here data is variable
Types of Variables

There are three types of variables in Java:


•local variable
•instance variable
•static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that
the variable exists.
A local variable cannot be defined with "static" keyword.

2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an
instance variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not shared
among instances.

3) Static variable
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.
Example to understand the types of variables in java

[Link] class A
2.{
3. static int m=100;//static variable
4. void method()
5. {
6. int n=90;//local variable
7. }
8. public static void main(String args[])
9. {
10. int data=50;//instance variable
11. }
12.}//end of class
Java Variable Example: Add Two Numbers

[Link] class Simple{


[Link] static void main(String[] args){
[Link] a=10;
[Link] b=10;
[Link] c=a+b;
[Link](c);
7.}
8.}

Output:
20
Java Variable Example: Widening

[Link] class Simple{


[Link] static void main(String[] args){
[Link] a=10;
[Link] f=a;
[Link](a);
[Link](f);
7.}}

Output:
10
10.0
Java Variable Example: Narrowing (Typecasting)

[Link] class Simple{


[Link] static void main(String[] args){
[Link] f=10.5f;
4.//int a=f;//Compile time error
[Link] a=(int)f;
[Link](f);
[Link](a);
8.}}
Output:
10.5
10
Operators:
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.

There are many types of operators in Java which are given below:

•Unary Operator,
•Arithmetic Operator,
•Shift Operator,
•Relational Operator,
•Bitwise Operator,
•Logical Operator,
•Ternary Operator and
•Assignment Operator.
Java Operator Precedence
Operator Type Category Precedence
Unary postfix expr++ expr--
prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%


additive +-
Shift shift << >> >>>
Relational comparison < > <= >= instanceof
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ?:
Assignment assignment = += -= *= /= %= &= ^= |= <<= >>=
>>>=
Java Unary Operator

The Java unary operators require only one operand. Unary operators are used to
perform various operations i.e.:

•incrementing/decrementing a value by one


•negating an expression
•inverting the value of a boolean
Java Unary Operator Example: ++ and –

[Link] class OperatorExample{


[Link] static void main(String args[]){
[Link] x=10;
[Link](x++);//10 (11)
[Link](++x);//12
[Link](x--);//12 (11)
[Link](--x);//10
8.}}
Output:
10
12
12
10
Java Unary Operator Example 2: ++ and –

[Link] class OperatorExample{


[Link] static void main(String args[]){
[Link] a=10;
[Link] b=10;
[Link](a++ + ++a);//10+12=22
[Link](b++ + b++);//10+11=21
7.
8.}}

Output:
22
21
Java Arithmetic Operators

Java arithmetic operators are used to perform addition, subtraction,


multiplication, and division. They act as basic mathematical operations.
Java Arithmetic Operator Example

[Link] class OperatorExample{


[Link] static void main(String args[]){
[Link] a=10;
[Link] b=5;
[Link](a+b);//15
[Link](a-b);//5
[Link](a*b);//50
[Link](a/b);//2
[Link](a%b);//0
10.}}

Output:
15
5
50
20
Java Left Shift Operator

The Java left shift operator << is used to shift all of the bits in a value to the left
side of a specified number of times.
Java Left Shift Operator Example

[Link] class OperatorExample{


[Link] static void main(String args[]){
[Link](10<<2);//10*2^2=10*4=40
[Link](10<<3);//10*2^3=10*8=80
[Link](20<<2);//20*2^2=20*4=80
[Link](15<<4);//15*2^4=15*16=240
7.}}

Output:
40
80
80
240
Java Right Shift Operator

The Java right shift operator >> is used to move the value of the left
operand to right by the number of bits specified by the right operand.
Java Right Shift Operator Example

[Link] OperatorExample{
[Link] static void main(String args[]){
[Link](10>>2);//10/2^2=10/4=2
[Link](20>>2);//20/2^2=20/4=5
[Link](20>>3);//20/2^3=20/8=2
6.}}

Output:
2
5
2
Java AND Operator Example: Logical && and Bitwise &

The logical && operator doesn't check the second condition if the first
condition is false. It checks the second condition only if the first one is true.
The bitwise & operator always checks both conditions whether first condition
is true or false.
[Link] class OperatorExample{
[Link] static void main(String args[]){
[Link] a=10;
[Link] b=5;
[Link] c=20;
[Link](a<b&&a<c);//false && true = false
[Link](a<b&a<c);//false & true = false
8.}}

Output:
false
false
Java OR Operator Example: Logical || and Bitwise |

The logical || operator doesn't check the second condition if the first
condition is true. It checks the second condition only if the first one is false.

The bitwise | operator always checks both conditions whether first


condition is true or false.
[Link] class OperatorExample{
[Link] static void main(String args[]){
[Link] a=10;
[Link] b=5;
[Link] c=20;
[Link](a>b||a<c);//true || true = true
[Link](a>b|a<c);//true | true = true
8.//|| vs |
[Link](a>b||a++<c);//true || true = true
[Link](a);//10 because second condition is not checked
[Link](a>b|a++<c);//true | true = true
[Link](a);//11 because second condition is checked
13.}}

Output:
true
true
true
10
true
11
Java Ternary Operator

Java Ternary operator is used as one line replacement for if-then-else statement
and used a lot in Java programming.

It is the only conditional operator which takes three operands.


Java Ternary Operator Example

[Link] class OperatorExample{


[Link] static void main(String args[]){
[Link] a=2;
[Link] b=5;
[Link] min=(a<b)?a:b;
[Link](min);
7.}}

Output:
2
Java Assignment Operator

Java assignment operator is one of the most common operators.

It is used to assign the value on its right to the operand on its left.
Java Assignment Operator Example

[Link] class OperatorExample{


[Link] static void main(String args[]){
[Link] a=10;
[Link] b=20;
5.a+=4;//a=a+4 (a=10+4)
6.b-=4;//b=b-4 (b=20-4)
[Link](a);
[Link](b);
9.}}

Output:
14
16
Control Structures:
Java compiler executes the code from top to bottom. The statements in the code are executed according to the
order in which they appear. However, Java provides statements that can be used to control the flow of Java
code. Such statements are called control flow statements. It is one of the fundamental features of Java, which
provides a smooth flow of program.

Java provides three types of control flow statements.


[Link] Making statements
1. if statements
2. switch statement

[Link] statements
1. do while loop
2. while loop
3. for loop
4. for-each loop

[Link] statements
1. break statement
2. continue statement
Decision-Making statements:

As the name suggests, decision-making statements decide which statement to


execute and when. Decision-making statements evaluate the Boolean expression
and control the program flow depending upon the result of the condition provided.
There are two types of decision-making statements in Java, i.e., If statement and
switch statement.

1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the
program is diverted depending upon the specific condition. The condition of the If
statement gives a Boolean value, either true or false. In Java, there are four types of
if-statements given below.
[Link] if statement
[Link]-else statement
[Link]-else-if ladder
[Link] if-statement
Let's understand the if-statements one by one.

1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a
Boolean expression and enables the program to enter a block of code if the expression
evaluates to true.

Syntax of if statement is given below.

[Link](condition) {
[Link] 1; //executes when condition is true
3.}
[Link] class Student {
[Link] static void main(String[] args) {
[Link] x = 10;
[Link] y = 12;
[Link](x+y > 20) {
[Link]("x + y is greater than 20");
7.}
8.}
9.}

Output:
x + y is greater than 20
2) if-else statement
The if-else statement is an extension to the if-statement, which uses another
block of code, i.e., else block. The else block is executed if the condition of the
if-block is evaluated as false.

Syntax:

[Link](condition) {
[Link] 1; //executes when condition is true
3.}
[Link]{
[Link] 2; //executes when condition is false
6.}
[Link] class Student {
[Link] static void main(String[] args) {
[Link] x = 10;
[Link] y = 12;
[Link](x+y < 10) {
[Link]("x + y is less than 10");
7.} else {
[Link]("x + y is greater than 20");
9.}
10.}
11.}
Output:
x + y is greater than 20
3) if-else-if ladder:

The if-else-if statement contains the if-statement followed by multiple else-


if statements. In other words, we can say that it is the chain of if-else
statements that create a decision tree where the program may enter in the
block of code where the condition is true. We can also define an else
statement at the end of the chain.
Syntax of if-else-if statement is given below.

[Link](condition 1) {
[Link] 1; //executes when condition 1 is true
3.}
[Link] if(condition 2) {
[Link] 2; //executes when condition 2 is true
6.}
[Link] {
[Link] 2; //executes when all the conditions are false
9.}
[Link] class Student {
[Link] static void main(String[] args) {
[Link] city = "Delhi";
[Link](city == "Meerut") {
[Link]("city is meerut");
6.}else if (city == "Noida") {
[Link]("city is noida");
8.}else if(city == "Agra") {
[Link]("city is agra");
10.}else {
[Link](city);
12.}
13.}
14.}

Output:
Delhi
4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another
if or else-if statement.

Syntax of Nested if-statement is given below.

[Link](condition 1) {
[Link] 1; //executes when condition 1 is true
[Link](condition 2) {
[Link] 2; //executes when condition 2 is true
5.}
[Link]{
[Link] 2; //executes when condition 2 is false
8.}
9.}
[Link] class Student {
[Link] static void main(String[] args) {
[Link] address = "Delhi, India";
4.
[Link]([Link]("India")) {
[Link]([Link]("Meerut")) {
[Link]("Your city is Meerut");
8.}else if([Link]("Noida")) {
[Link]("Your city is Noida");
10.}else {
[Link]([Link](",")[0]);
12.}
13.}else {
[Link]("You are not living in India");
15.}
Output:
16.}
Delhi
17.}
Switch Statement:

In Java, Switch statements are similar to if-else-if statements. The switch statement
contains multiple blocks of code called cases and a single case is executed based on the
variable which is being switched. The switch statement is easier to use instead of if-else-if
statements. It also enhances the readability of the program.
•The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
•Cases cannot be duplicate
•Default statement is executed when any of the case doesn't match the value of expression.
It is optional.
•Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
•While using switch statements, we must notice that the case expression will be of the same
type as the variable. However, it will also be a constant value.
The syntax to use the switch statement is given below.
[Link] (expression){
2. case value1:
3. statement1;
4. break;
5. .
6. .
7. .
8. case valueN:
9. statementN;
10. break;
11. default:
12. default statement;
13.}
[Link] class Student implements Cloneable {
[Link] static void main(String[] args) {
[Link] num = 2;
[Link] (num){
[Link] 0:
[Link]("number is 0");
[Link];
[Link] 1:
[Link]("number is 1");
[Link];
[Link]:
[Link](num);
13.}
14.} Output:
15.} 2
Loop Statements

In programming, sometimes we need to execute the block of code repeatedly while some
condition evaluates to true. However, loop statements are used to execute the set of
instructions in a repeated order. The execution of the set of instructions depends upon a
particular condition.

In Java, we have three types of loops that execute similarly. However, there are differences
in their syntax and condition checking time.
[Link] loop
[Link] loop
[Link]-while loop
Java for loop

In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check
the condition, and increment/decrement in a single line of code. We use the for loop only
when we exactly know the number of times, we want to execute the block of code.

[Link](initialization, condition, increment/decrement) {


2.//block of statements
3.}
[Link] class Calculattion {
[Link] static void main(String[] args) {
3.// TODO Auto-generated method stub
[Link] sum = 0;
[Link](int j = 1; j<=10; j++) {
[Link] = sum + j;
7.}
[Link]("The sum of first 10 natural numbers is " + sum);

9.}
10.}

Output:
The sum of first 10 natural numbers is 55
Java while loop

The while loop is also used to iterate over the number of statements multiple times.
However, if we don't know the number of iterations in advance, it is recommended to use a
while loop. Unlike for loop, the initialization and increment/decrement doesn't take place
inside the loop statement in while loop.

It is also known as the entry-controlled loop since the condition is checked at the start of the
loop. If the condition is true, then the loop body will be executed; otherwise, the statements
after the loop will be executed.

The syntax of the while loop is given below.


[Link](condition){
2.//looping statements
3.}
[Link] class Calculation {
[Link] static void main(String[] args) {
3.// TODO Auto-generated method stub
[Link] i = 0;
[Link]("Printing the list of first 10 even numbers \n");
[Link](i<=10) {
[Link](i);
8.i = i + 2;
9.}
10.}
11.}

Output:
Printing the list of first 10 even numbers 0 2 4 6 8 10
Java do-while loop

The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iteration is not known and we have to execute the loop at
least once, we can use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in advance.

The syntax of the do-while loop is given below.


[Link]
2.{
3.//statements
4.} while (condition);
[Link] class Calculation {
[Link] static void main(String[] args) {
3.// TODO Auto-generated method stub
[Link] i = 0;
[Link]("Printing the list of first 10 even numbers \n");
[Link] {
[Link](i);
8.i = i + 2;
9.}while(i<=10);
10.}
11.}

Output:
Printing the list of first 10 even numbers
0 2 4 6 8 10
Jump Statements

Jump statements are used to transfer the control of the program to the specific statements.
In other words, jump statements transfer the execution control to the other part of the
program. There are two types of jump statements in Java, i.e., break and continue.

Java break statement

As the name suggests, the break statement is used to break the current flow of the program
and transfer the control to the next statement outside a loop or switch statement. However,
it breaks only the inner loop in the case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be
written inside the loop or switch statement.
[Link] class BreakExample {
2.
[Link] static void main(String[] args) {
4.// TODO Auto-generated method stub
[Link](int i = 0; i<= 10; i++) {
[Link](i);
[Link](i==6) {
[Link];
9.}
10.}
11.}
12.}

Output:
0123456
[Link] class Calculation {
2.
[Link] static void main(String[] args) {
4.// TODO Auto-generated method stub
5.a:
[Link](int i = 0; i<= 10; i++) {
7.b:
[Link](int j = 0; j<=15;j++) {
9.c:
[Link] (int k = 0; k<=20; k++) {
[Link](k);
[Link](k==5) {
[Link] a;
14.} } } } } }

Output:
012345
Java continue statement

Unlike break statement, the continue statement doesn't break the loop, whereas, it skips
the specific part of the loop and jumps to the next iteration of the loop immediately.
[Link] class ContinueExample {
[Link] static void main(String[] args) {
3.// TODO Auto-generated method stub
[Link](int i = 0; i<= 2; i++) {
[Link] (int j = i; j<=5; j++) {
[Link](j == 4) {
[Link];
8.}
[Link](j);
10.} } } }
Output:
01235
1235
235
Method Overloading:
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.

If we have to perform only one operation, having same name of the methods increases the
readability of the program.

Suppose you have to perform addition of the given numbers but there can be any number
of arguments, if you write the method such as a(int,int) for two parameters, and
b(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behavior of the method because its name differs.
So, we perform method overloading to figure out the program quickly.
Advantage of method overloading
Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java


[Link] changing number of arguments
[Link] changing the data type
1) Method Overloading: changing no. of arguments
In this example, we have created two methods, first add() method
performs addition of two numbers and second add method performs
addition of three numbers.
In this example, we are creating static methods so that we don't need to
create instance for calling methods.
[Link] Adder{
[Link] int add(int a,int b){return a+b;}
[Link] int add(int a,int b,int c){return a+b+c;}
4.}
[Link] TestOverloading1{
[Link] static void main(String[] args){
[Link]([Link](11,11));
[Link]([Link](11,11,11));
9.}}
Output:
22 33
2) Method Overloading: changing data type of arguments

In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.
[Link] Adder{
[Link] int add(int a, int b){return a+b;}
[Link] double add(double a, double b){return a+b;}
4.}
[Link] TestOverloading2{
[Link] static void main(String[] args){
[Link]([Link](11,11));
[Link]([Link](12.3,12.6));
9.}}

Output:
22
24.9
Math Class:
Java Math class provides several methods to work on math calculations like min(), max(),
avg(), sin(), cos(), tan(), round(), ceil(), floor(), abs() etc.
Unlike some of the StrictMath class numeric methods, all implementations of the
equivalent function of Math class can't define to return the bit-for-bit same results. This
relaxation permits implementation with better-performance where strict reproducibility is
not required.

If the size is int or long and the results overflow the range of value, the methods
addExact(), subtractExact(), multiplyExact(), and toIntExact() throw
an ArithmeticException.
For other arithmetic operations like increment, decrement, divide, absolute value, and
negation overflow occur only with a specific minimum or maximum value. It should be
checked against the maximum and minimum value as appropriate.
[Link] class JavaMathExample1
2.{
3. public static void main(String[] args)
4. {
5. double x = 28;
6. double y = 4;
7. // return the maximum of two numbers
8. [Link]("Maximum number of x and y is: " +[Link](x, y));
9. // return the square root of y
10. [Link]("Square root of y is: " + [Link](y));
11. //returns 28 power of 4 i.e. 28*28*28*28
12. [Link]("Power of x and y is: " + [Link](x, y));
13. // return the logarithm of given value
14. [Link]("Logarithm of x is: " + [Link](x));
15. [Link]("Logarithm of y is: " + [Link](y));
16. // return the logarithm of given value when base is 10
17. [Link]("log10 of x is: " + Math.log10(x));
18. [Link]("log10 of y is: " + Math.log10(y));
19. // return the log of x + 1
20. [Link]("log1p of x is: " +Math.log1p(x));
1.// return a power of 2
2. [Link]("exp of a is: " +[Link](x));
3. // return (a power of 2)-1
4. [Link]("expm1 of a is: " +Math.expm1(x));
5. } }

Output:
Maximum number of x and y is: 28.0
Square root of y is: 2.0
Power of x and y is: 614656.0
Logarithm of x is: 3.332204510175204
Logarithm of y is: 1.3862943611198906
log10 of x is: 1.4471580313422192
log10 of y is: 0.6020599913279624
log1p of x is: 3.367295829986474
exp of a is: 1.446257064291475E12
expm1 of a is: 1.446257064290475E12
Java Math Methods

The [Link] class contains various methods for performing basic numeric operations
such as the logarithm, cube root, and trigonometric functions etc. The various java math
methods are as follows:
Basic Math methods
Method Description
[Link]() It will return the Absolute value of the given value.

[Link]() It returns the Largest of two values.

[Link]() It is used to return the Smallest of two values.

[Link]() It is used to round of the decimal numbers to the


nearest value.
[Link]() It is used to return the square root of a number.

[Link]() It is used to return the cube root of a number.


[Link]() It returns the value of first argument raised to the
power to second argument.
[Link]() It is used to find the sign of a given value.

[Link]() It is used to find the smallest integer value that is


greater than or equal to the argument or mathematical
integer.
Trigonometric Math Methods
Method Description

[Link]() It is used to return the trigonometric Sine value of a


Given double value.

[Link]() It is used to return the trigonometric Cosine value of a


Given double value.

[Link]() It is used to return the trigonometric Tangent value of


a Given double value.

[Link]() It is used to return the trigonometric Arc Sine value of


a Given double value

[Link]() It is used to return the trigonometric Arc Cosine value


of a Given double value.

[Link]() It is used to return the trigonometric Arc Tangent value


of a Given double value.
Logarithmic Math Methods
Method Description

[Link]() It returns the natural logarithm of a double value.

Math.log10() It is used to return the base 10 logarithm of


a double value.

Math.log1p() It returns the natural logarithm of the sum of the


argument and 1.

[Link]() It returns E raised to the power of a double value,


where E is Euler's number and it is approximately
equal to 2.71828.

Math.expm1() It is used to calculate the power of E and subtract one


from it.
Arrays In Java:
Normally, an array is a collection of similar type of elements which has contiguous memory
location.

Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where
we store similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.

Unlike C/C++, we can get the length of the array using the length member. In C/C++, we
need to use the sizeof operator.
In Java, array is an object of a dynamically generated class. Java array inherits the Object
class, and implements the Serializable as well as Cloneable interfaces. We can store primitive
values or objects in an array in Java. Like C/C++, we can also create single dimentional or
multidimentional arrays in Java.

Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.
Advantages

•Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.

•Random access: We can get any data located at an index position.


Disadvantages

Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size
at runtime. To solve this problem, collection framework is used in Java which grows
automatically.
Types of Array in java

There are two types of array.


•Single Dimensional Array
•Multidimensional Array
Single Dimensional Array in Java

Syntax to Declare an Array in Java


[Link][] arr; (or)
[Link] []arr; (or)
[Link] arr[];

Instantiation of an Array in Java


arrayRefVar=new datatype[size];
1.//Java Program to illustrate how to declare, instantiate, initialize
2.//and traverse the Java array.
[Link] Testarray{
[Link] static void main(String args[]){
[Link] a[]=new int[5];//declaration and instantiation
6.a[0]=10;//initialization
7.a[1]=20;
8.a[2]=70;
9.a[3]=40;
10.a[4]=50;
11.//traversing array
[Link](int i=0;i<[Link];i++)//length is the property of array
[Link](a[i]);
14.}}

Output:
10 20 70 40 50
Declaration, Instantiation and Initialization of Java Array

We can declare, instantiate and initialize the java array together by:
[Link] a[]={33,3,4,5};//declaration, instantiation and initialization
1.//Java Program to illustrate the use of declaration, instantiation
2.//and initialization of Java array in a single line
[Link] Testarray1{
[Link] static void main(String args[]){
[Link] a[]={33,3,4,5};//declaration, instantiation and initialization
6.//printing array
[Link](int i=0;i<[Link];i++)//length is the property of array
[Link](a[i]);
9.}}

Output:
33 3 4 5
ArrayIndexOutOfBoundsException
The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length of
the array in negative, equal to the array size or greater than the array size while traversing the
array.
1.//Java Program to demonstrate the case of
2.//ArrayIndexOutOfBoundsException in a Java Array.
[Link] class TestArrayException{
[Link] static void main(String args[]){
[Link] arr[]={50,60,70,80};
[Link](int i=0;i<=[Link];i++){
[Link](arr[i]);
8.}
9.}}

Output:
Exception in thread "main" [Link].
ArrayIndexOutOfBoundsException: 4 at [Link]([Link])
50 60 70 80
Multidimensional Array in Java
In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in Java


[Link][][] arrayRefVar; (or)
[Link] [][]arrayRefVar; (or)
[Link] arrayRefVar[][]; (or)
[Link] []arrayRefVar[];
Example to instantiate Multidimensional Array in Java
[Link][][] arr=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional Array in Java
[Link][0][0]=1;
[Link][0][1]=2;
[Link][0][2]=3;
[Link][1][0]=4;
[Link][1][1]=5;
[Link][1][2]=6;
[Link][2][0]=7;
[Link][2][1]=8;
[Link][2][2]=9;
1.//Java Program to illustrate the use of multidimensional array
[Link] Testarray3{
[Link] static void main(String args[]){
4.//declaring and initializing 2D array
[Link] arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6.//printing 2D array
[Link](int i=0;i<3;i++){
8. for(int j=0;j<3;j++){
9. [Link](arr[i][j]+" ");
10. }
11. [Link]();
12.}
13.}}

Output:
123245445
Addition of 2 Matrices in Java
Let's see a simple example that adds two matrices.
1.//Java Program to demonstrate the addition of two matrices in Java
[Link] Testarray5{
[Link] static void main(String args[]){
4.//creating two matrices
[Link] a[][]={{1,3,4},{3,4,5}};
[Link] b[][]={{1,3,4},{3,4,5}};
7.//creating another matrix to store the sum of two matrices
[Link] c[][]=new int[2][3];
9.//adding and printing addition of 2 matrices
[Link](int i=0;i<2;i++){
[Link](int j=0;j<3;j++){
12.c[i][j]=a[i][j]+b[i][j];
[Link](c[i][j]+" ");
14.}
[Link]();//new line
16.}
17.}}
Output:
2 6 8 6 8 10
Multiplication of 2 Matrices in Java
In the case of matrix multiplication, a one-row element of the first matrix is multiplied by all
the columns of the second matrix which can be understood by the image given below.
1.//Java Program to multiply two matrices
[Link] class MatrixMultiplicationExample{
[Link] static void main(String args[]){
4.//creating two matrices
[Link] a[][]={{1,1,1},{2,2,2},{3,3,3}};
[Link] b[][]={{1,1,1},{2,2,2},{3,3,3}};
7.//
creating another matrix to store the multiplication of two matrices
[Link] c[][]=new int[3][3]; //3 rows and 3 columns
9.//multiplying and printing multiplication of 2 matrices
[Link](int i=0;i<3;i++){
[Link](int j=0;j<3;j++){
12.c[i][j]=0;
[Link](int k=0;k<3;k++)
14.{
15.c[i][j]+=a[i][k]*b[k][j];
16.}//end of k loop
[Link](c[i][j]+" "); //printing matrix element
2.}//end of j loop
[Link]();//new line
4.}
5.}}

Output:
666
12 12 12
18 18 18
Advantage of OOPs over Procedure-oriented programming language

1) OOPs makes development and maintenance easier, whereas, in a procedure-


oriented programming language, it is not easy to manage if code grows as project
size increases.

2) OOPs provides data hiding, whereas, in a procedure-oriented programming


language, global data can be accessed from anywhere.
Figure: Data Representation in Procedure-Oriented Programming
Figure: Data Representation in Object-Oriented Programming
3) OOPs provides the ability to simulate real-world event much more effectively. We
can provide the solution of real word problem if we are using the Object-Oriented
Programming language.
THANK YOU

You might also like